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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...