[英]Rspec for begin ... rescue block in rails
我正在编写一个测试,它应该验证当 object 创建保存时,确实捕获了异常。
begin
object.create!(item)
rescue => exception
exception.message
end
rspec
expect{ exception.message }.to eq("Validation failed: Item name can't be blank")
output 我得到:
Failure/Error: expect{ exception.message }.to eq("Validation failed: Item name can't be blank")
You must pass an argument rather than a block to `expect` to use the provided matcher (eq "Validation failed: Item name can't be blank"), or the matcher must implement `supports_block_expectations?`.
谁能帮我吗?
你不能这样测试你的代码,因为exception
变量只存在于rescue
块中。 相反,您需要调用要测试的方法并添加对它应该返回的内容的期望。
您的示例实际上没有可以调用的方法。 我想你的方法实际上是这样的:
def do_stuff_with(object, item)
begin
object.create!(item)
rescue => exception
exception.message
end
end
那么你应该能够有这样的期望:
expect(do_stuff_with(object, item)).to eq(
"Validation failed: Item name can't be blank"
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.