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
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(mail.to).to contain_exactly("firstname.lastname@example.org") expect(mail.from).to contain_exactly("email@example.com") end
first_recipient = method_that_creates_a_user aggregate_failures "mail sent" do expect(ActionMailer::Base.deliveries.last.to).to contain("firstname.lastname@example.org") expect(first_recipient.email).to match("email@example.com") 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