【问题标题】:Rspec testing raising and rescue of methodRspec 测试方法的提升和救援
【发布时间】: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


【解决方案1】:

您通常不想直接引发或挽救 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

如果您不知道(或关心)应该引发的特定异常或消息,但您希望 一些 异常会中断执行流程,那么您应该使用纯 @987654323 @匹配器。例如:

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

【讨论】:

  • 感谢您的帖子,但除非我误解,否则我不相信它解决了我的问题。 (我以标准错误为例,它通常是一个特定的错误。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多