有没有办法让Rspec设置一个被捕获的异常的期望?我想验证MyException是否会被引发,但是因为我正在捕获异常,所以Rspec似乎并不知道它曾经发生过。
begin
if success
do good stuff
else
raise MyException.new()
end
rescue MyException => e
clean up
end
我尝试过以下几件事但没有成功。 MyException.should_receive(:new)
和
Kernel.should_receive(:raise).with(MyException)
答案 0 :(得分:1)
您可以测试救援区的行为,而不是检查异常:
class Test
def my_method
if success
# do good stuff
else
raise MyException.new()
end
rescue MyException => e
clean_up
end
end
describe Test do
it "should clean up when unsuccessful" do
subject.stub(:success) { false }
subject.should_receive(:clean_up)
subject.my_method
end
end
答案 1 :(得分:1)
我想出了如何做我需要的事情。
class MyClass
def my_method
begin
if success
do good stuff
else
raise MyException.new
end
rescue MyException => e
# clean up
end
end
end
describe MyClass do
it "Expects caught exception" do
my_instance = MyClass.new()
my_instance.should_receive(:raise).with(any_instance_of(MyException))
my_instance.my_method()
end
end
感谢您的其他建议。
答案 2 :(得分:0)
我会这样做:
RSpec.describe "matching error message with string" do
it "matches the error message" do
expect { raise StandardError, 'this message exactly'}.
to raise_error('this message exactly')
end
end
逐字复制