2015-02-06 35 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