fluentassertions
fluentassertions copied to clipboard
Allow changing context for subsequent assertions
Background and motivation
Based on #2223.
It would be nice to have an API to be able to change the context for custom assertions. For example, I have the following extension to ReferenceTypeAssertions
that allows me to transform the value before asserting further:
type ReferenceTypeAssertions<'TSubject, 'TAssertions
when 'TAssertions :> ReferenceTypeAssertions<'TSubject, 'TAssertions>> with
member this.WhenTransformed(f: 'TSubject -> 'TTransformed) = f this.Subject
This allows me to do this:
result
.Should()
.MatchRegex(@"^\d{6}-\d{4}$", "the value should be formatted correctly")
.And.WhenTransformed(String.replace "-" "")
.Should()
.Be(input, "the value should be equal to the input ignoring spaces")
However, if the last one fails, it still uses the variable name result
as the context. This is confusing, because the value is no longer result
.
I know I can override the context using AssertionScope
, but I can't use that in WhenTransformed
because I don't actually assert anything there.
Another example is a custom assertions type OptionAssertions
I have made to assert (using a method BeSome
) an F# option
value to be Some _
, and then use Which
to continue asserting on the inner value. I can't use AssertionScope
because it's disposed once the AndWhichConstraint
is returned from BeSome
.
API Proposal
I really don't know how this can best be solved. But, at the very least, it seems to me I have to be able to call a new API in custom *Assertions
extension members, and that this API can not be based on IDisposable
.
API Usage
See above.
Alternative Designs
No response
Risks
No response
For what it's worth, I am no longer interested in this. As detailed in https://github.com/fluentassertions/fluentassertions/issues/2225#issuecomment-1636796736, I am creating a brand new F# assertions library inspired by FluentAssertions. That library will automatically support this feature with no end user hassle. Feel free to close.