Is there a way to properly test exception raising with implicit subjects in rspec?
For example, this fails:
describe 'test' do
subject {raise 'an exception'}
it {should raise_exception}
end
But this passes:
describe 'test' do
it "should raise an exception" do
lambda{raise 'an exception'}.should raise_exception
end
end
Why is this?
subject
accepts a block which returns the subject of the remainder.
What you want is this:
describe 'test' do
subject { lambda { raise 'an exception' } }
it { should raise_exception }
end
Edit: clarification from comment
This:
describe 'test' do
subject { foo }
it { should blah_blah_blah }
end
is more or less equivalent to
(foo).should blah_blah_blah
Now, consider: without the lambda
, this becomes:
(raise 'an exception').should raise_exception
See here that the exception is raised when the subject is evaluated (before should
is called at all). Whereas with the lambda, it becomes:
lambda { raise 'an exception' }.should raise_exception
Here, the subject is the lambda, which is evaluated only when the should
call is evaluated (in a context where the exception will be caught).
While the "subject" is evaluated anew each time, it still has to evaluate to the thing you want to call should
on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With