Useful RSpec matchers that you may not be using

Just sharing a couple RSpec matchers that I think are very useful but people doesn’t seem to know they even exist 🙂

all matcher

When I wanted to make sure that every element of an Enumerable, for example, should be an instance of Course, I would write:

it 'populates @catalog_courses only with courses' do
  assigns(:catalog_courses).each do |course|
    expect(course).to be_a(Course)
  end
end

But with the all matcher, its just:

it 'populates @catalog_courses only with courses' do
  expect(assigns(:catalog_courses)).to all( be_a(Course) )
end

I used the be_a matcher inside the all but you could use any other like: be_truthy or eq.

contain_exactly matcher

When I wanted to make sure that an Array should include a and b elements but in any order I would write something like:

it 'populates @courses with courses a, b and c' do
  courses = assigns(:courses)

  expect(courses).to include(a)
  expect(courses).to include(b)
  expect(courses).to include(c)
end

Now, using the contain_exactly matcher:

it 'populates @courses with courses a and b' do
  expect(assigns(:courses)).to contain_exactly(a, b, c)
end

Hope you learned something new here. Leave in the comments any other awesome matcher that you think other people may not be using 😀

1 Comment

  • Since`contain_exactly` is a matcher testing the set equality, `contain_exactly(a, b, c)` not only asserts the subject includes a, b and c, but also states that the subject is of length 3

Leave a Comment