Thursday, November 18, 2010

RSpec 2: #raise_error

I was writing a spec and attempted to use #raise_error. To my surprise, it wasn't working. Here's what I did and how I solved it.

Code to be tested:
class TestClass
  def run; raise "Error"; end
end

Spec:
it 'should raise' do
  TestClass.new.run.should raise_error
end

To my surprise, the error wasn't caught and it failed with a raised error. There was no syntax error and the way I wrote it felt very natural, but it wasn't behaving the way I thought it should. However, upon further investigation, I realized the usage of #raise_error is on a Proc or lambda.

The spec should have been:
it 'should raise' do
  Proc.new { TestCase.new.run }.should raise_error
  lambda { TestCase.new.run }.should raise_error
end

And if you really want it to read well:
it 'should raise' do
  expect { TestCase.new.run }.to raise_error
end

No comments:

Post a Comment