Reputation: 5745
Is there a way to rspec test if an error was raised and rescued? If I have a rescue, my rspec test does not see the raised error, only results in the rescue?
module MyApp
def some_method(msg)
raise StandardError.new(msg)
end
def second_method(msg)
begin
count = 0
some_method(msg)
rescue StandardError=> e
puts e
count = 1
end
end
end
RSpec.describe Myapp do
describe "#some_method" do
it "should raise error" do
expect {
some_method("this is an error")
}.to raise_error(StandardError) {|e|
expect(e.message).to eql "this is an error"
}
end
end
# this fails, as the error is not raised
describe "#second_method" do
it should raise error and rescue do
expect {
a = second_method("this is an error and rescue")
}.to raise_error(StandardError) {|e|
expect(e.message).to eql "this is an error and rescue"
expect(a) = 1
}
end
end
end
Upvotes: 1
Views: 5098
Reputation: 84373
You generally don't want to raise or rescue StandardError directly because it's pretty uninformative, and won't catch errors outside of the StandardError hierarchy. Instead, you generally want to test that a specific exception was raised, or that a specific error class or error message was raised.
If you know the custom or built-in exception class that you want, or the specific error message, then test for that explicitly. For example:
it 'should raise an ArgumentError exception' do
expect { MyApp.new.foo }.to raise_error(ArgumentError)
end
it 'should raise MyCustomError' do
expect { MyApp.new.foo }.to raise_error(MyCustomError)
end
it 'should raise StandardError with a custom message' do
msg = 'this is a custom error and rescue'
expect { MyApp.new.foo }.to raise_error(msg)
end
If you don't know (or care about) the specific exception or message that should be raised, but you expect some exception to interrupt the execution flow, then you should use a bare raise_error matcher. For example:
it "should raise an exception" do
expect { MyApp.new.foo }.to raise_error
end
Upvotes: 2