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

标签 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 测试还很陌生,所以非常感谢任何帮助。请解释你的答案是做什么的,以便我学习。

最佳答案

编写检查 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 to value, 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/

相关文章:

ruby - 如何在 Hyperstack 中导入 Material 图标?

ruby - 使用 Aruba 和 Bundler 测试基于 Ruby 的 CLI

ruby-on-rails-3 - 无法在circleci中运行 Elasticsearch 以使我的rspec能够通过Elasticsearch?

ruby-on-rails - 如何开始测试 Rails 应用程序?

ruby-on-rails - Rails 如何测试一个方法接收 block 参数与 Rspec

ruby-on-rails - rails noob 学习 rspec 的最佳方法是什么?

ruby - 如何使用 RSpec 测试具有默认参数的 Ruby 类

ruby-on-rails - 仅将 namespace 用作参数

ruby-on-rails - Mechanize 访问链接并获取页面标题

ruby-on-rails - Ruby 从数组中随机选择有时会重复返回相同的值