简体   繁体   English

如何在 RSPEC 中测试链调用?

[英]How to test chain call in RSPEC?

I have call looks like我有电话看起来像

1) foo1 => MyModel.where(id: my_model_ids)
2) foo2 => MyModel.where('date > :new_date', {new_date: DateTime.new(0)})
3) foo2.sum(:count)

How can I test this call Chain ?我如何测试这个调用链? I tried this我试过这个

where_mock = instance_double(ActiveRecord::Relation)
result_mock = instance_double(ActiveRecord::Relation)

filter = 'date > :new_date'
new_data_hash = {new_date: DateTime.new(0)}


expect(where_mock).to receive(:where).with(filter, new_data_hash).and_return(result_mock)
expect(result_mock).to receive(:sum)

But it didn't work但它没有用

I think you're looking for receive_message_chain , https://relishapp.com/rspec/rspec-mocks/docs/working-with-legacy-code/message-chains我认为您正在寻找receive_message_chainhttps: receive_message_chain

The example they give is:他们举的例子是:

allow(Article).to receive_message_chain("recent.published") { [Article.new] }

It's worth noting that use of this method is often symptomatic of a code smell.值得注意的是,使用这种方法通常是代码异味的征兆。

If here you're testing that a message is received rather than the output, you can test the first method call in isolation, stub the result, and then test that the stub receives the second method call.如果您在这里测试接收的是消息而不是输出,您可以单独测试第一个方法调用,存根结果,然后测试存根是否接收第二个方法调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM