RSpec 3 allows chaining multiple expectations

Updated . Posted . Visible to the public. Repeats.

When you are using lambdas in RSpec to assert certain changes of a call, you know this syntax:

expect { playlist.destroy }.to change { Playlist.count }.by(-1)

While you can define multiple assertions through multiple specs, you may not want to do so, e.g. for performance or for the sake of mental overhead.

Multiple expectations on the same subject

RSpec allows chaining expectations simply by using and.

expect { playlist.destroy }
  .to change { Playlist.count }.by(-1)
  .and change { Video.count }.by(0)

The above example will call playlist.destroy only once, but test both assertions.

Note

When you chain multiple Capybara Show archive.org snapshot matchers using and, Capybara will retry all matchers if any of the matchers fail.

Alternative expectations

In addition to and, RSpec also offers or which means that only one condition needs to be satisfied. Example from the docs:

expect(light.color)
  .to eq("green")
  .or eq("yellow")
  .or eq("red")

See also

Arne Hartherz
Last edit
Henning Koch
Keywords
compound, expectations, alternative, union, intersection, or
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2018-11-05 10:37)