Ruby on rails 无法将非存根方法与接收\u消息\u链rspec一起使用
我对接收消息链rspec 3.6有一个奇怪的问题Ruby on rails 无法将非存根方法与接收\u消息\u链rspec一起使用,ruby-on-rails,rspec,Ruby On Rails,Rspec,我对接收消息链rspec 3.6有一个奇怪的问题 allow_any_instance_of(Order).to receive_message_chain('line_items.find') {LineItem.first} 当我执行order.line\u items而不是返回集合时,它会返回一个对象,这不是我想要的 任何建议???当您告诉RSpec在特定对象上设置接收消息链('line\u items.find')时,它需要在适当的位置设置正确的存根以使链工作 第一个RSpec将方
allow_any_instance_of(Order).to receive_message_chain('line_items.find')
{LineItem.first}
当我执行order.line\u items而不是返回集合时,它会返回一个
对象,这不是我想要的
任何建议???当您告诉RSpec在特定对象上设置
接收消息链('line\u items.find')
时,它需要在适当的位置设置正确的存根以使链工作
第一个RSpec将方法行\u项
存根在对象上。接下来它需要存根方法find
,但是这个方法需要存根在方法行\u项的返回值上。由于我们对该方法进行了存根,RSpec需要给出一个返回值,该值可能是存根的目标
因此RSpec将方法line\u items
的返回值设置为匿名双精度,该双精度具有方法find
存根。因此,一旦将接收消息链与'line\u items.find'
一起设置,调用line\u items
时,对象将始终返回匿名双精度。由于您使用了allow\u any\u instance\u of
,这意味着方法line\u items
现在在Order
的所有实例上都存根
如果可能的话,我建议您考虑从您的规范中删除allow\u any\u instance\u of
和receive\u message\u chain
,因为如果您确实无法更改代码的设计,它们实际上是规范中使用的快捷方式
但是,如果不可能,您可以删除接收消息\u链
,然后自己设置链
line_items_stub = double
# or line_items_stub = Order.new.line_items
# or line_items_stub = [LineItem.new, LineItem.new]
# or line_items_stub = the object that you want
allow_any_instance_of(Order).
to receive(:line_items).
and_return(line_items_stub)
allow(line_items_stub).to receive(:find)
如果您能够删除allow_any_instance(允许任何实例)
,您可以使用调用,以便在具体实例上真正实现行项目,并将消息链保留在其上。您的RSpec是什么,您要测试的代码是什么?你预期会发生什么?实际发生了什么?这是日晒的问题。在收到信息链(“a.b.c”)后,我不能再使用a.b.d了@JagdeepSinghmakes很多意义。