5

I have a function that I want to test raises an exception on an input, but that exception also carries some more information than just a plain message, and I want to test that too. So I did something like this as seen in the rspec documentation:

it 'raises the correct exception' do
   expect { my_call }.to raise_error do |error|
     expect(error.some_field).to eq('some data')
   end
end

This works great, however it runs afoul of the RSpec/MultipleExpectations cop:

RSpec/MultipleExpectations: Example has too many expectations [2/1]

From what I can tell it is impossible to use raise_error in block form like this without more than one expect, so what gives? Is there some way to somehow save the raised exception outside the example so I can spec it normally, without doing something horrible involving rescue in the specs? Or should I use a custom raise_custom_error matcher?

3 Answers 3

6

Rubocop by default I think enables the warning that you see which says to only have one expect in each it block. You can disable this in rubocop.yml by adding this:

# Disables "Too many expectations."
RSpec/MultipleExpectations:
  Enabled: false

Or if you only want to disable it for your specific spec you can do so by adding comments like this, note you can disable any rubocop rule this way by using the rule name in comments:

# rubocop:disable RSpec/MultipleExpectations
it 'raises the correct exception' do
  expect { my_call }.to raise_error do |error|
    expect(error.some_field).to eq('some data')
  end
end
# rubocop:enable RSpec/MultipleExpectations

it 'does something else' do
  expect(true).to be true
end

For more rubocop syntax options see this answer

1
  • 1
    The MultipleExpectations cop comes from rubocop-rspec not rubocop core. This extension is in my experience more awkward to work with than core, so it is indeed tempting to disable bits of it. Or maybe it's just not as well documented (not as many discussions like this to help people), so I shall do my bit and add an answer showing how to do it without disabling!
    – Harry Wood
    Nov 20, 2023 at 11:43
0

Rubocop is warning you that it's code smell, please listen to it as that kind of testing is very brittle; defining an expectation inside of an expectation is likely to yield flaky results, as will defining multiple independent expectations within the same example (the example run will always halt at the first failed expectation). If you're testing that an exception is raised, your example block typically only needs to check for the error type and/or message like this (see the raise_error documentation):

it 'raises the correct exception' do
  expect { call }.to raise_error(ErrorKlass, 'expected message')
end

If it's necessary to do something like validate arguments the exception was raised with, use mock or spy syntax; however, the more valuable thing to test for in that scenario is the thing your code does with that information after recovering from the exception. There's no real benefit to validating your exception had some attribute beyond its error message, but if your exception recovery logic is passing that along in a payload to your logger, it's beneficial to write a mock or spy that validates your logger receives a message including the specific arguments you expect to see passed along.

If you're truly facing the rare scenario where it's appropriate for an example to contain multiple expectations that can't be and-chained, use the aggregate_failures API (but don't nest expectations inside of other expectations).

4
  • "no real benefit to validating your exception had some attribute beyond its error message" seems a bit presumptuous. It's a unit test after all. But I take it that was your reason for voting my answer down. Anyway I think we can agree that both of our answers are better than just telling people to disable the cop!
    – Harry Wood
    Jan 30 at 9:01
  • @HarryWood I hit downvote by accident intending to downvote the answer advising to suppress rubocop and it wouldn't let me undo it until some amount of time had passed, I was going to go back and undo it later but if you're going to be aggressive about it I won't bother because it has valid info but is not great advice for this scenario. An exception shouldn't have attributes to validate beyond type and message (e.g., ruby-doc.org/3.3.0/Exception.html), and to overload an Exception model or response in any way that would make those tests work would be an anti-pattern.
    – Allison
    Jan 30 at 9:26
  • Sorry I wasn't intending to come across aggressive
    – Harry Wood
    Jan 30 at 10:14
  • 1
    Sorry I genuinely had only intended to downvote the other answer, but SO says the downvote is locked in unless the answer is edited
    – Allison
    Feb 8 at 3:05
-1

You can always disable RSpec/MultipleExpectations cop, but you should really ask yourself how to rewrite it in a way which keeps rubocop (and rubocop-rspec) happy. Something like this should work:

  it 'raises the correct exception' do
    expect { my_call }.to raise_error(
      having_attributes(some_field: 'some data')
    )
  end

If we want to do more checks on the error class we can use "composable argument matchers" i.e. add in a .and like so:

  it 'raises the correct exception' do
    expect { my_call }.to raise_error(
      an_instance_of(RuntimeError)
      .and(having_attributes(some_field: 'some data'))
    )
  end

A similar question was discussed in the rubocop-rspec repo here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.