ruby-on-rails - 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 个失败
解决方案
根据您的示例,第二行@product.recalculate
引发了一个实际异常,因此引发了错误。假设recalculate
方法是在@product
对象中定义的,这应该足以测试它。
it "Test" do
expect { @product.recalculate }.to raise_error(StandardError)
end
推荐阅读
- yaml - Helm 模板三元集运算符
- java - Swagger 3.0.0:没有 SwaggerConfig 和 @Profile 就无法在生产中禁用
- c# - 生成对象时出现错误
- vb.net - 如何在 VB.net 中计算单独班级的平均值?
- unity3d - 如何在 Unity 中通过 C# 将按钮组件的转换选项设置为“无”?
- java - 在 HibernateConfiguration 中使用环境时 ApplicationContext 出错
- java - 一款带有文字图形的 RPG 游戏
- c# - 如何从 C# 调用 PostgreSQL 13 存储过程?
- javascript - 在两个数组之间迭代以查找匹配值的最有效方法是什么?
- c# - C# TypeKind 的字符串?是 TypeKind.Class