Testing exceptions with RSpec

I’m new to ruby and rspec. I wrote a ruby function and wanted to check whether it throws an exception or not in a certain situation with rspec, but I realized should_raise function no longer worked in the rspec version I was using (1.2.2). I tried to find information on the Internet and I found that I should use raise_error.

However, when I wrote something like:

it “description” do
    ObjectName.new(“parameterName”).should raise_error
end

It did not work. Finally I learned the correct way – using lambda:

it “description” do
    lambda{
ObjectName.new(“parameterName”)}.should raise_error
end

Wanted to post this here and hope it can be helpful for people in the similar need.

 

5 thoughts on “Testing exceptions with RSpec

Leave a Reply

Your email address will not be published. Required fields are marked *