Writing RSpec Matchers

Learn about RSpec tools and how to import and implement new custom matchers examples.

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

RSpec tools

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

Importing custom matchers

Normally custom matchers are placed in the spec/support folder, which can be imported when RSpec starts. We need to explicitly require the custom matcher file in the rails_helper file to import our matcher. RSpec 3.1 contains a commented line in the rails_helper that we can uncomment in the setup to load the entire spec/support directory automatically. We can also choose to directly import individual matcher files at the beginning of the spec files that use them.

Custom matchers example

Here’s an example of converting the size comparisons to an RSpec custom matcher:

Get hands-on with 1400+ tech skills courses.