Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

rspec3

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.

like image 930
La-comadreja Avatar asked Apr 29 '15 19:04

La-comadreja


2 Answers

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
like image 150
La-comadreja Avatar answered Oct 14 '22 06:10

La-comadreja


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
like image 30
Michał Młoźniak Avatar answered Oct 14 '22 05:10

Michał Młoźniak