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

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.


RSpec 2

expect { some_method }.to raise_errorexpect { some_method }.to raise_error(SomeError)expect { some_method }.to raise_error("oops")expect { some_method }.to raise_error(/oops/)expect { some_method }.to raise_error(SomeError, "oops")expect { some_method }.to raise_error(SomeError, /oops/)expect { some_method }.to raise_error(...){|e| expect(e.data).to eq "oops" }# Rspec also offers to_not:expect { some_method }.to_not raise_error...

Note: raise_error and raise_exception are interchangeable.

RSpec 1

lambda { some_method }.should raise_errorlambda { some_method }.should raise_error(SomeError)lambda { some_method }.should raise_error(SomeError, "oops")lambda { some_method }.should raise_error(SomeError, /oops/)lambda { some_method }.should raise_error(...){|e| e.data.should == "oops" }# Rspec also offers should_not:lambda { some_method }.should_not raise_error...

Note: raise_error is an alias for raise_exception.

Documentation: https://www.relishapp.com/rspec

RSpec 2:

RSpec 1:


Instead of lambda, use expect to:

   expect { some_method }.to raise_error

This is applies for more recent versions of rspec, i.e. rspec 2.0 and up.

See the doco for more.