使用rspec观察`allow`和`have_received`的奇怪行为>> [

问题描述 投票:0回答:1
我在规格中使用allowhave_received时遇到问题

我有一个名为Obj的模型,该模型与一个名为belongs_to的模型具有Parent关系。 Parent模型与has_many具有Obj关系。

Obj模型中,我定义了一种称为child_method的方法。在Parent模型中,我定义了一种名为calls_child_method的方法,该方法遍历与之关联的每个Obj,并让它们调用child_method

我正在编写一个规范来测试此行为,如下所示,但它总是失败:

describe 'parent calls_child_method' do let(:obj) { Obj.create } before do allow(obj).to receive(:child_method) end it 'should call child_method' do obj.parent.calls_child_method expect(obj).to have_received(:child_method) end end

输出:

expected: 1 time with any arguments received: 0 times with any arguments

但是,当我使用allow_any_instance_of进行间谍/打桩时,这似乎过去了:

describe 'parent calls_child_method' do let(:obj) { Obj.create } before do allow(obj).to receive(:child_method) end it 'should call child_method' do expect_any_instance_of(Obj).to receive(:child_method) obj.parent.calls_child_method end end

或者如果我直接调用子方法:

describe 'parent calls_child_method' do let(:obj) { Obj.create } before do allow(obj).to receive(:child_method) end it 'should call child_method' do obj.child_method expect(obj).to have_received(:child_method) end end

在所有这些中,我已经验证了所创建的Obj实例实际上是通过使用child_method调试来查看其正在被调用的。byebug

有人可以帮我理解为什么规范/间谍的行为是这样的吗?

我在我的规范中使用allow和have_received时遇到问题,我有一个名为Obj的模型,该模型与一个称为Parent的模型有一个Emirates_to关系。父模型与...

ruby-on-rails rspec rspec-rails rspec3
1个回答
0
投票
这个问题困扰了我很多年。这就是我对正在发生的事情的理解。

在失败的情况下,obj是对新创建的Obj.create的引用。通过调用expect(obj).to have_received(:child_method),期望精确引用obj应该收到child_method

© www.soinside.com 2019 - 2024. All rights reserved.