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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)