ruby - "wrong number of arguments"错误的 RSpec 测试在某些环境中失败

标签 ruby rspec ruby-2.3

我的测试有问题。

我有这个规范:

context 'when no section is supplied' do
  it 'raises an ArgumentError regarding the missing section_id argument' do
    expect do
      described_class.with_section
    end.to raise_error(ArgumentError)
      .with_message /wrong number of arguments \(given 0\, expected 1\)/
  end
end

在某些环境中,消息是:

ArgumentError: wrong number of arguments (0 for 1)

在其他环境中,消息是:

ArgumentError: wrong number of arguments (given 0, expected 1)

所以我有一个测试在我的 Mac 上通过但在另一台计算机上失败。

我该如何解决这个问题?

最佳答案

差异似乎是由于运行测试的 Ruby 版本所致。 Ruby 2.2 和更早的版本使用类似

的消息报告此错误
"ArgumentError: wrong number of arguments (0 for 1)"

Ruby 2.3 报告此错误的消息如下

"ArgumentError: wrong number of arguments (given 0, expected 1)"

(这更容易理解)。

对于大多数应用程序来说,解决此问题的正确方法是在您开发和/或部署程序的所有机器上运行相同版本的 Ruby。让一个应用程序在多个主要版本的 Ruby 上运行意味着在这些版本上测试它,这意味着在每台开发人员机器上都有所有支持的版本,这比在一个版本上解决更多的工作。这也意味着放弃新版本 Ruby 中的好东西。

如果你确实需要你的程序兼容多个版本的Ruby,你可以测试RUBY_VERSION常量:

context 'when no section is supplied' do
  it 'raises an ArgumentError regarding the missing section_id argument' do
    message = RUBY_VERSION.start_with? '2.3' \
      ? "wrong number of arguments (given 0, expected 1)" \
      : "wrong number of arguments (0 for 1)"
    expect { described_class.with_section }.to raise_error(ArgumentError).
      with_message /#{Regexp.escape message}/
  end
end

关于ruby - "wrong number of arguments"错误的 RSpec 测试在某些环境中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35872676/

相关文章:

ruby-on-rails - 将Elasticsearch与RSpec和Factorygirl一起使用

ruby-on-rails - Ruby如何将Namespace的模块功能委托(delegate)给Namespace::Base内部类

ruby - if/else 语句中的变量将不起作用

ruby - 为什么 Ruby 对指数方程式的变量和数字有不同的处理方式?

ruby - 什么是 "asynchronous exception handling"

ruby-on-rails - rails rspec -(第二次测试)预期响应为 < :redirect>, 但为 <200>

ruby - 在 Ruby 的 DSL 中使用 procs

ruby-on-rails - 名称错误 : uninitialized constant Faker

ruby-on-rails - Rails View 路径未被重置

ruby - Ruby 2.3.1 中 set 的除法函数