Custom Matchers

As you work with rspec-expectations, you may find yourself wishing for a project-specific should notation to make your assertions more legible. For example, let’s say you wanted to write the following step to test a Book class:

rspec/examples.rb
 
this_book.should please(​'developers'​)
 
 
class​ Book
 
def​ pleases?(people)
 
people == ​'developers'
 
end
 
end

rspec-expectations doesn’t ship with a should please() matcher, but you can write a custom matcher and throw it in your env.rb.

rspec/examples.rb
 
RSpec::Matchers.define :please ​do​ |people|
 
match ​do​ |book|
 
book.pleases?(people)
 
end
 
end

When used in moderation, custom matchers can make your Cucumber step definitions easy to read and maintain.

Get Cucumber Recipes 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.