Write Your Own RSpec Matchers

RSpec’s built-in matchers are flexible, but sometimes you have behavior patterns you specify multiple times in your code and the existing matchers don’t quite cover it. Sometimes this is because the specification requires multiple steps, and sometimes it’s because the generic matcher doesn’t quite match the code’s intent.

RSpec provides tools for creating your own custom matchers to cover just such an eventuality. A basic matcher is really simple. Let’s say we wanted a custom matcher to measure project size in points. Rather than say expect(project.size).to eq(5) we’d say expect(project).to be_of_size(5). It’s a little contrived, but work with me.

Normally custom matchers are placed in the spec/support folder, ...

Get Rails 4 Test Prescriptions now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.