Skip to Content
Course content

102: RSpec Matchers In Depth

Click on the "Edit" button in the top corner of the screen to edit your slide content.

You've likely already spent some time using expect().to eq(). It's the workhorse of RSpec, and for a lot of basic tests, it's all you need. But as you start building more complex systems, you'll notice a pattern: you're writing three or four lines of tests to verify one single conceptual change. I see this all the time in code reviews. We're testing the implementation of the data structure rather than the intent of the behavior.

The trap of the generic equality check

Imagine we're building a simple ShoppingCart. We want to make sure that when we add a product, the cart actually holds that product and the count goes up. A naive approach—the kind I used to write early in my career—looks something like this:

it "adds an item to the cart" do
  cart = ShoppingCart.new
  item = Product.new(name: "Mechanical Keyboard")
  
  cart.add(item)
  
  expect(cart.items.count).to eq(1)
  expect(cart.items.first).to eq(item)
end

On the surface, this works. It's green. But it's brittle. I'm explicitly checking the count and then peering into the array to see if the first element is the item. If I later change the ShoppingCart to store items in a Hash or a Set for performance reasons, this test breaks—not because the feature is broken, but because the test was too interested in the internal array structure.

Capturing intent with specialized matchers

The goal is to write tests that describe what should happen, not how the data is stored. RSpec gives us specialized matchers that do the heavy lifting for us. Instead of checking the count and the first element separately, we can use include and the change matcher.

it "adds an item to the cart" do
  cart = ShoppingCart.new
  item = Product.new(name: "Mechanical Keyboard")
  
  expect { cart.add(item) }.to change { cart.items.count }.by(1)
  expect(cart.items).to include(item)
end

This is a subtle shift, but it's a powerful one. The change matcher allows us to wrap the action (adding the item) and the expectation (the count increasing) into a single atomic operation. It reads like a sentence: "I expect that adding an item to change the items count by one."

When 'eq' tells you nothing about why it failed

The biggest trade-off here isn't actually about the code's cleanliness—it's about the failure messages. When expect(cart.items.first).to eq(item) fails, RSpec tells you that nil does not equal #<Product...>. That's fine, but it doesn't tell you why.

If you use match_array, for instance, RSpec does something clever. If you expected [:apple, :orange] but got [:apple, :banana], RSpec won't just say "they aren't equal." It will explicitly tell you that :orange was expected but missing, and :banana was an unexpected extra. I've spent hours debugging tests that used eq on large arrays, squinting at a wall of text to find one missing element. Using a matcher like match_array or include turns a ten-minute hunt into a five-second fix.

Ultimately, the rule of thumb I follow is this: if you find yourself calling .count, .first, or .any? inside an expect block, you're probably using the wrong matcher. Look for one that describes the relationship between the objects rather than the state of the variable.




📋 Practical Task

Refactoring the UserRegistration Service Tests

You've inherited a test suite for a UserRegistration service. The current tests are "brittle"—they rely on checking array indexes and boolean flags instead of using RSpec's more expressive matchers. Your goal is to refactor the test file to use specialized matchers.

The Scenario: The UserRegistration service takes a user's email and a list of "interest tags" (e.g., ['ruby', 'testing', 'architecture']). When a user registers, the service should: 1. Increase the total registered user count by 1. 2. Ensure the user's tags list contains all the provided interests, regardless of the order they were saved in.

The Brittle Code:

# current_spec.rb
it "registers a user with tags" do
  service = UserRegistration.new
  tags = ['ruby', 'testing']
  
  initial_count = User.count
  service.register("dev@example.com", tags)
  expect(User.count).to eq(initial_count + 1)
  
  user = User.last
  expect(user.tags.count).to eq(2)
  expect(user.tags[0]).to eq('ruby')
  expect(user.tags[1]).to eq('testing')
end

Your Task: Rewrite the test block above. Replace the manual count tracking with a change matcher and replace the index-based tag checks with a single match_array matcher. This will ensure the test remains green even if the database returns the tags in a different order.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.