首页 > 解决方案 > Rspec:测试未处理的异常

问题描述

在我的公共方法#recalculate 中,调用私有的method1. 此方法抛出异常“标准错误”。我想测试这种情况,但是出现错误。

注意:我不想处理异常。

def recalculate
  method_1
end

private
def method_1
    ## do some calculation
    raise StandardError.new("Test")
end

Rspec 测试用例:

  it "Test" do
    expect { @product.recalculate.recalculate }.to raise_error(StandardError)
    @product.recalculate
  end

1) Product.Test 
  Failure/Error: @product.recalculate
   StandardError:
     Test
   (required)>'

在 1.39 秒内完成 1 个示例,1 个失败

标签: ruby-on-railsrubyruby-on-rails-3ruby-on-rails-4rspec

解决方案


根据您的示例,第二行@product.recalculate引发了一个实际异常,因此引发了错误。假设recalculate方法是在@product对象中定义的,这应该足以测试它。

it "Test" do
  expect { @product.recalculate }.to raise_error(StandardError)
end

推荐阅读