3

I have an issue in my test.

I have this spec:

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

In some environments the message is:

ArgumentError: wrong number of arguments (0 for 1)

In other environments the message is:

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

So I have a test that passes on my Mac and fails on another computer.

How can I fix this?

sawa
  • 165,429
  • 45
  • 277
  • 381
Roberto Pezzali
  • 2,484
  • 2
  • 27
  • 56

2 Answers2

2

The difference appears to be due to the Ruby version under which the tests are being run. Ruby 2.2 and earlier report this error with a message like

"ArgumentError: wrong number of arguments (0 for 1)"

Ruby 2.3 reports this error with a message like

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

(which is much easier to understand).

The right way to address this for most applications is to run the same version of Ruby on all machines on which you develop and/or deploy the program. Making an application work on multiple major versions of Ruby means testing it on those versions, which means having all supported versions on every developer machine, which is more work than settling on one version. It also means giving up nice things in newer versions of Ruby.

If you really need your program to be compatible with multiple versions of Ruby, you can test the RUBY_VERSION constant:

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
Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
1

Why not just do:

.with_message /wrong number of arguments \((0 for 1|given 0, expected 1)\)/
sawa
  • 165,429
  • 45
  • 277
  • 381