4

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?

Seawaves32
  • 103
  • 6

1 Answers1

7

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

lacostenycoder
  • 10,623
  • 4
  • 31
  • 48