Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write expect {}.to raise_error when rspec's syntax is configured with only should

I have this configuration on rspec:

config.expect_with :rspec do |c|
  c.syntax = :should
end

It makes the expect {}.to raise_error invalid, how could I write this error raising test with should syntax?

like image 744
steveyang Avatar asked Dec 11 '22 16:12

steveyang


2 Answers

I would suggest to use this only if the most-recent RSpec expect { code() }.to raise_error syntax is not available to you:

lambda { foo( :bad_param ) }.should raise_error

or

lambda { foo( :bad_param ) }.should raise_error( ArgumentError )

Replacing foo( :bad_param ) with whatever Ruby code you wish to assert fails, and ArgumentError with whatever exception class you expect the failure to raise.

like image 171
Neil Slater Avatar answered Dec 14 '22 06:12

Neil Slater


In tests where I could use the expect syntax, I prefer to define that test in its own describe block, put the test content (ie expect { <this_content> }) into a stabby lambda, stick it in a new subject, and refer to it in an it block, like so:

describe "some test that raises error" do
  let(:bad_statement) { something_that_raises_an_error }
  subject { -> { bad_statement } }
  it { should raise_error }
end

If you wanted, you could also just do away with the let statement altogether and put its content directly in the subject.

like image 35
Paul Fioravanti Avatar answered Dec 14 '22 06:12

Paul Fioravanti