为什么rspec加倍:==两次

时间:2015-02-06 15:22:41

标签: ruby rspec mocking

我正在进行一项测试,这出乎意料地失败了。它说= =两次调用==。是因为它也是该方法的一个参数吗?

这是我所说的

的简单例子
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 个答案:

答案 0 :(得分:1)

查看TestDouble中的rspec-mocks课程,我们发现:

# 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有意地颠倒了这个电话。假装你有两个单独的双打,double_1 == double2会按照这些方式做点什么:

  • 致电double_1 == double2
  • 正如我们所见,这会反过来,但它会将double_1double_1的代理交换出来:double2 == __mock_proxy
  • 然后double2会再次撤消通话(otherdouble_1的代理人):other == __mock_proxy
  • 由于otherProxy对象而非TestDouble,因此会调用另一个==方法(此时此方法正在比较两个Proxy个对象),我们终于得到了比较。

正如你所看到的,==实际上被调用了3个不同的东西:第一个双重,第二个双重,最后是第一个双重代理。因为你的第一个和第二个双倍是相同的,所以它会被调用两次。

请参阅TestDouble's == methodProxy's == method