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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)