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层次结构之外的错误。相反,您通常希望测试是否引发了特定的异常,或者是否引发了具体的错误类或错误消息。

如果您知道所需的自定义或内置异常类,或者特定的错误消息,那么请显式测试。例如:

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

如果您不知道(或不关心(应该引发的特定异常或消息,但您希望某个异常会中断执行流,那么您应该使用裸raise_error匹配器。例如:

it "should raise an exception" do
expect { MyApp.new.foo }.to raise_error
end

相关内容

  • 没有找到相关文章

最新更新