【发布时间】:2020-09-08 18:14:25
【问题描述】:
有没有办法 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
【问题讨论】:
-
这可能是 X/Y 问题。根据定义,如果您已经挽救了一个异常,那么除非您重新引发它,否则它不再被“引发”。如果要跟踪先前处理的异常,则需要管理自己的存储对象以在救援/确保子句之外持续跟踪 $!和 $@。
-
$!还有 $@mean?
-
Ruby 通过维护一些神秘的系统全局变量来向 Larry Wall 致敬,其中
$!和$@是两个。如果您在文件顶部使用require 'English',则可以使用更具描述性的名称$ERROR_INFO和$ERROR_POS来称呼它们
标签: ruby rspec rspec-rails ruby-on-rails-6 raiserror