[英]Rspec for begin ... rescue block in rails
I am writing a test which should verify that when the object creation saves, indeed the exception is caught.我正在编写一个测试,它应该验证当 object 创建保存时,确实捕获了异常。
begin
object.create!(item)
rescue => exception
exception.message
end
rspec rspec
expect{ exception.message }.to eq("Validation failed: Item name can't be blank")
output I got: 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?`.
Can anyone help me out?谁能帮我吗?
You cannot test your code like that because the exception
variable only exists in the rescue
block.你不能这样测试你的代码,因为
exception
变量只存在于rescue
块中。 Instead, you need to call the method you want to test and add an expectation of what it should return.相反,您需要调用要测试的方法并添加对它应该返回的内容的期望。
Your example actually doesn't have such a method that could be called.您的示例实际上没有可以调用的方法。 I imagine that your method actually looks like this:
我想你的方法实际上是这样的:
def do_stuff_with(object, item)
begin
object.create!(item)
rescue => exception
exception.message
end
end
Then you should be able to have an expectation like this:那么你应该能够有这样的期望:
expect(do_stuff_with(object, item)).to eq(
"Validation failed: Item name can't be blank"
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.