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]) }

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store