Writing 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 you wanted a custom matcher to measure project size in points. Rather than say expect(project.size).to eq(5) you’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 5 Test Prescriptions now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.