2016-03-08 74 views
3

我的測試中有一個問題。在某些環境中,「參數數量錯誤」RSpec測試失敗

我有這個天賦:

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並在另一臺計算機上失敗。

我該如何解決這個問題?

回答

1

爲什麼不只是做:

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

這種差異似乎是由於正在運行測試的Ruby版本所致。紅寶石2.2和更早的報告這個錯誤有消息像

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

紅寶石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