首页 > 解决方案 > 如何在 RSPEC 中测试链调用?

问题描述

我有电话看起来像

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

我如何测试这个调用链?我试过这个

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)

但它没有用

标签: ruby-on-railsrubyrspec

解决方案


我认为您正在寻找receive_message_chainhttps://relishapp.com/rspec/rspec-mocks/docs/working-with-legacy-code/message-chains

他们给出的例子是:

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

值得注意的是,使用这种方法通常是代码异味的症状。

如果您在此处测试接收到的是消息而不是输出,则可以单独测试第一个方法调用,存根结果,然后测试存根接收到第二个方法调用。


推荐阅读