Ruby,rspec测试方法时出现预期错误

时间:2018-10-29 21:01:34

标签: ruby rspec

我有一个看起来像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测试的新手,因此能提供任何帮助。请解释您的答案是什么,以便我学习。

1 个答案:

答案 0 :(得分:3)

编写检查raise_error的规范时,必须对{}使用块语法expect

expect { my_method(p1, p2, p3, p4, bad5) }.to raise_error(ArgumentError)

this question's answers中有更深入的解释,但是您要求提供一个解释,所以我给您一个缩写:

大多数rspec匹配器都是值匹配器。那意味着像这样:

expect(some_method).to eq(value)

真的在说:

  

执行some_method并获取其返回值,然后将其返回值与value进行比较,并根据该比较判断此规范的成功或失败

当您尝试测试某些具有副作用的代码时,例如可能引发异常,rspec需要接收一段代码才能运行。有点像:

expect { <some block of code> }.to raise_error(ArgumentError)
  

执行<some block of code>,然后将执行该代码时发生的情况与预期发生的情况进行比较,并根据该比较判断此规范的成败

This answer针对以上链接的问题,详细介绍了何时需要使用expect {}和何时需要使用expect()