如何解决Rspec测试提出和挽救方法
是否存在一种方法可以rspec测试是否引发并挽救了错误?如果可以进行救援,我的rspec测试不会看到引发的错误,只会导致救援?
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
解决方法
通常,您不希望直接引发或挽救StandardError,因为它非常无用,并且不会捕获StandardError hierarchy之外的错误。相反,您通常想测试是否引发了特定的异常,或者引发了特定的错误类或错误消息。
如果知道所需的自定义或built-in exception class或特定的错误消息,请显式测试。例如:
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
如果您不知道(或关心)应该引发的特定异常或消息,但是您希望 some 异常会中断执行流程,则应使用裸露的{{ 3}}匹配器。例如:
it "should raise an exception" do
expect { MyApp.new.foo }.to raise_error
end
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。