Defining a Matcher Class

Most of the time, you’ll use the DSL for defining custom matchers. Sometimes, though, you need a little more control or might prefer to define the matcher in the most explicit way possible.

As we mentioned earlier in the chapter, any Ruby object that implements the matcher protocol can serve as an RSpec matcher. It’s pretty easy to translate the DSL example from the previous section into a Ruby class that has the required methods.

The Ruby Class

This class is about a page of code, but it has a lot of similarities to the shorter DSL version we wrote. Take a look here, and then we’ll call out a few highlights afterward:

1: class​ HaveABalanceOf

Get Effective Testing with RSpec 3 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.