Posted over 1 year ago. Visible to the public. Repeats.

RSpec: How to aggregate failures

RSpec >= 3.3 added aggregate_failures, which allows multiple failures in an example and list them all, rather than aborting on the first failure.

This can be used:

  • In the global configuration
  • With the tag :aggregate_failures (our preferred option in case every expectations should be aggregated)
  • With the method aggregate_failures

Below is an example, which shows why aggregating failures are useful.


aggregate_failures do first_expectation_object = false second_expectation_object = false third_expectation_object = true expect(first_expectation_object).to be(true), "first expectation failed" # will fail expect(second_expectation_object).to be(true), "second expectation failed" # will fail expect(third_expectation_object).to be(true), "third expectation failed" # will pass end
(::) failed steps (::) Got 2 failures from failure aggregation block "multiple expectations": 1) first expectation failed 2) second expectation failed

As you can see, the test is not being interrupted by the first two falsy expectations, the third expectation passed without a message.

This can be handy if you are testing for multiple values, which map to one context, e. g. mail components, in order to provide better readability of your tests or to even make clear a tests fail reason due to some dependency:

aggregate_failures "email header" do expect(mail.subject).to match("Welcome") expect( contain_exactly("") expect(mail.from).to contain_exactly("") end
first_recipient = method_that_creates_a_user aggregate_failures "mail sent" do expect( contain("") expect( match("") end

In the last example first_recipient has been created in a different file, so it might not be obvious (in more complicated cases, imagine a list of more recipients) that method_that_creates_a_user actually creates a user with the mail address

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Jakob Scholz
Last edit:
about 1 year ago
by Besprechungs-PC
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Jakob Scholz to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more