我有一个看起来像 build_object(arg1, arg2, arg3, arg4, arg5)
的方法 我想在为 arg5 传递特定值时测试此方法。
我正在尝试类似的东西
expect(my_method(p1, p2, p3, p4, bad5)).to raise_error(ArgumentError)
我收到以下错误:
ArgumentError:
The expect syntax does not support operator matchers, so you must pass a matcher to `#to`.
我对 Ruby 和 rspec 测试还很陌生,所以非常感谢任何帮助。请解释你的答案是做什么的,以便我学习。
最佳答案
编写检查 raise_error
的规范时,您必须使用 block 语法 {}
对于 expect
:
expect { my_method(p1, p2, p3, p4, bad5) }.to raise_error(ArgumentError)
this question's answers 中有更深入的解释,但你要求解释,所以我给你一个简短的解释:
大多数 rspec 匹配器都是值匹配器。这意味着像这样的东西:
expect(some_method).to eq(value)
实际上是在说:
perform
some_method
and get its return value, then compare its return value tovalue
, and judge the success or failure of this spec on that comparison
当您尝试测试一些有副作用的代码时,例如可能引发异常,rspec 需要接收要运行的代码块。它有点像:
expect { <some block of code> }.to raise_error(ArgumentError)
perform
<some block of code>
, and then compare what happens when that code is executed to what is expected to happen, and judge the success or failure of this spec on that comparison
This answer对于上述链接的问题,详细说明了何时需要使用 expect {}
以及何时需要使用 expect()
.
关于Ruby,rspec 测试方法时出现预期错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53053754/