Andrew Andrew - 7 days ago 6
Ruby Question

How do I `expect` something which raises exception in RSpec?

I have a method which performs some actions on Cat model and in case of incorrect input raises an exception:

context "hungry cat" do
it { expect { eat(what: nil) }.to raise_error }
end


What I want to do is to check whether this method change cats status, like that:

context "hungry cat" do
it { expect { eat(what: nil) }.to raise_error }
it { expect { eat(what: nil) }.not_to change(cat, :status) }
end


The problem is that since
eat(what: nil)
will raise an exception the second
it
will fail no matter what. So, is it possible to ignore exception and check some condition?

I know that it's possible to do something like:

it do
expect do
begin
eat(what: nil)
rescue
end
end.not_to change(cat, :status)
end


But it's way too ugly.

Answer

You could use the "rescue nil" idiom to shorten what you already have:

it { expect { eat(what: nil) rescue nil }.not_to change(cat, :status) }