How to Use Rspec's Should_Raise with Any Kind of Exception

How to use RSpec's should_raise with any kind of exception?

expect { some_method }.to raise_error

RSpec 1 Syntax:

lambda { some_method }.should raise_error

See the documentation (for RSpec 1 syntax) and RSpec 2 documentation for more.

How do I `expect` something which raises exception in RSpec?

You could use the "rescue nil" idiom to shorten what you already have:

it { expect { eat(what: nil) rescue nil }.not_to change(cat, :status) }

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

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

How to raise an exception in an RSpec test

Like this, for example

expect(object).to receive(:save).and_raise(ActiveRecord::StaleObjectError)

bitly raise error exception rspec test

As you can see from the docs - https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/raise-error-matcher - the raise error matcher can take a second parameter of string or regex to match against the exceptions message

expect { whatever }.to raise_error(BitlyError, "ALREADY_A_BITLY_LINK")


Related Topics



Leave a reply



Submit