rspec-support icon indicating copy to clipboard operation
rspec-support copied to clipboard

Enhance ObjectFormatter to transcribe values as their memoized let blocks or instance variable names

Open walski opened this issue 2 years ago • 2 comments

Subject of the issue

I am constantly spending time answering the question "which object is this?" when writing specs.

This is especially true for expectations on arrays or hashes, where one often deals with more than 1 value.

An example for this would be:

@one = Something.new(1)
@two = Something.new(2)
@three = Something.new(3)
@four = Something.new(4)

one_two_three = [@one, @two, @three]

expect(one_two_three).to contain_exactly(@one, @two, @four)

This would then report an error similar to this:

Failure/Error: expect(one_two_three).to contain_exactly(@one, @two, @four)
     
       expected collection contained:  ["#<struct Something id=1>", "#<struct Something id=2>", "#<struct Something id=4>"]
       actual collection contained:    [#<struct Something id=1>, #<struct Something id=2>, #<struct Something id=3>]
       the missing elements were:      ["#<struct Something id=4>"]
       the extra elements were:        [#<struct Something id=3>]

In this case it's pretty straight-forward to figure out the diff and the objects causing it. But this gets convoluted very fast with real world (e.g. ActiveRecord) objects.

Instead I would love if this would resemble something like this:

Failure/Error: expect(one_two_three).to contain_exactly(@one, @two, @four)
     
       expected collection contained:  [@one, @two, @four]
       actual collection contained:    [@one, @two, @three]
       the missing elements were:      [@four]
       the extra elements were:        [@three]

It should be fairly easy to do that at least for instance variables and let-blocks.

Would you be open to a PR in that direction? What would be a good approach to do this? Should this be an opt-in configuration? Should it be not in rspec-support at all and live in it's own gem?

Would love to hear your feedback :) Thank you!

Thorben

walski avatar Nov 14 '23 15:11 walski