2015-02-06 34 views
0

我有一個測試,我正在與此工作意外失敗。它是說==會在double上調用兩次。是否因爲它也是該方法的一個論據?爲什麼rspec雙打收到:==兩次

這就是我講的

require 'rspec' 
describe 'rspec test doubles' do 
    let(:a_double) { double('a_double') } 

    it 'should only call == once' do 
     expect(a_double).to receive(:==).and_return(true) 
     a_double == a_double 
    end 
end 

的蒸餾的例子,這是我所得到的,當我運行這個測試

F 

Failures: 

    1) rspec test doubles should only call == once 
    Failure/Error: expect(watir_driver).to receive(:==).and_return(true) 
     (Double "watir_driver").==(*(any args)) 
      expected: 1 time with any arguments 
      received: 2 times with any arguments 
    # ./double_spec.rb:7:in `block (2 levels) in <top (required)>' 

Finished in 0.019 seconds (files took 0.26902 seconds to load) 
1 example, 1 failure 

Failed examples: 

rspec ./double_spec.rb:6 # rspec test doubles should only call == once 

回答

1

rspec-mocksTestDouble類看,我們找到這個:

# This allows for comparing the mock to other objects that proxy such as 
# ActiveRecords belongs_to proxy objects. By making the other object run 
# the comparison, we're sure the call gets delegated to the proxy 
# target. 
def ==(other) 
    other == __mock_proxy 
end 

所以它看起來像rspec purposefu lly撤回電話。假設你有兩個獨立的雙打,做double_1 == double2會做沿着這些路線的東西:

  • 呼叫double_1 == double2
  • 正如我們看到的,那麼這將扭轉它,但它會換出double_1double_1的代理:double2 == __mock_proxy
  • 然後double2會再次撥打電話(otherdouble_1的代理):other == __mock_proxy
  • 由於otherProxy對象,而不是TestDouble,不同==方法被調用(其在這一點上比較兩個Proxy對象),並且我們最終得到了比較。

正如你所看到的,==實際上被3個獨立的東西調用:第一個double,第二個double,最後是第一個double的代理。因爲你的第一個和第二個double是相同的,它會被調用兩次。

TestDouble's == methodProxy's == method

+0

你知道,當他們開始表現呀?它看起來像rspec 3.0沒有 – 2015-02-06 16:10:04

+0

@DaneAndersen我不知道。我很驚訝它沒有在3.0中 - '=='的定義已經存在了將近3年了,並且查看3.0的代碼,它仍然執行'other == __mock_proxy'的事情。 – 2015-02-06 16:21:47