Block Matchers

Block matchers observe a block of code and are used to specify a side effect that occurs when the block runs. They take the form:

 expect​ { some_code }.to matcher

As with value matchers, block matchers can be negated by using not_to or to_not rather than to.

Mutation

The change matcher captures a value before running the block (old_value) and again after running the block (new_value). The value can be specified in two ways:

 expect​ { do_something }.to change(obj, ​:attr​)
 # or
 expect​ { do_something }.to change { obj.attr }

It supports a rich fluent interface for specifying further details about the mutation:

MatcherPasses if…

change { }

old_value != new_value

change { }.by(x)

(new_value - old_value) == x

change { }.by_at_least(x) ...

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.