RSpec 3: expect object.do_something to NOT raise a particular kind of error
Asked Answered
B

2

13

I would like to test whether a particular method does NOT raise an error of class AError. It can raise BError, ArgumentError, almost any other kind of error, or no error, just not AError. Is there any non-deprecated (as of RSpec 3) way to do this?

I tried

expect { object.do_something }.not_to raise_error(AError)

but I get

ArgumentError:
   `expect { }.not_to raise_error(SpecificErrorClass)` is not valid,
    use `expect { }.not_to raise_error` (with no args) instead

The problem with the argument-less approach is that the test will fail on ANY kind of error, when it should pass on anything except for an AError.

This documentation doesn't seem to help: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/raise-error-matcher

It seems that the old versions of RSpec have a way to handle this type of situation, and I don't understand what happened to RSpec in the new version.

So I'm confused. Thanks.

Bakemeier answered 29/4, 2015 at 19:10 Comment(0)
B
12

This specific syntax solved the problem:

it 'do_something does not raise AError' do
  begin
    expect { object.do_something }.not_to raise_error
  rescue RSpec::Expectations::ExpectationNotMetError => e
    expect(e.message).not_to include 'AError'
  end
end
Bakemeier answered 29/4, 2015 at 20:5 Comment(0)
U
1

You can read discussion about why this was removed here https://github.com/rspec/rspec-expectations/issues/231

If you really must to test this case, you can do this differently:

begin
  object.do_something
rescue StandardError => e
  # expect e to not be AError
end
Ursi answered 29/4, 2015 at 19:40 Comment(1)
this isn't the right syntax. If an error is thrown, this won't hit the rescue block. The test will just fail and say that do_something threw the error.Bakemeier

© 2022 - 2024 — McMap. All rights reserved.