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

RSpec test of "wrong number of arguments" error fails in some environments

我的测试有问题。

我有这个规格:

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)"

(这样比较容易理解)

对于大多数应用程序,解决此问题的正确方法是 运行 在您开发 and/or 部署该程序的所有计算机上使用相同版本的 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

为什么不直接做:

.with_message /wrong number of arguments \((0 for 1|given 0, expected 1)\)/