Names for Let Objects
When using RSpec to test a method that returns a list of objects, e.g. an ActiveRecord scope, we often encounter the following kind of confusing test output, where we can’t easily deduce which results differed from our expectations.
What if it could instead look like this?
Now our result (results.sh) is highly readable. The cost is, we have to delve a bit into the private implementation of RSpec. Having used this idea for the past year or so, I’ve been happy with it.
UPDATE:
Ajay Sharma responded with a great technique to simplify this pattern:
This can be taken a step further with a custom matcher like
RSpec::Matchers.define(:match_named_array) do |expected|
match do |actual|
@actual = names_for_let_objects(actual)
expect(@actual).to match_array(expected)
end diffable
end
allowing a simpler test like
specify { expect(User.all).to match_named_array([:bob]) }