Read more

RSpec 3 allows chaining multiple expectations

Arne Hartherz
November 05, 2018Software engineer at makandra GmbH

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)
Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot

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

Posted by Arne Hartherz to makandra dev (2018-11-05 11:37)