我正在进行一项测试,这出乎意料地失败了。它说= =两次调用==。是因为它也是该方法的一个参数吗?
这是我所说的
的简单例子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
答案 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_1
与double_1
的代理交换出来:double2 == __mock_proxy
double2
会再次撤消通话(other
为double_1
的代理人):other == __mock_proxy
。other
是Proxy
对象而非TestDouble
,因此会调用另一个==
方法(此时此方法正在比较两个Proxy
个对象),我们终于得到了比较。正如你所看到的,==
实际上被调用了3个不同的东西:第一个双重,第二个双重,最后是第一个双重代理。因为你的第一个和第二个双倍是相同的,所以它会被调用两次。