如何测试 RSPEC 中的链式调用?
How to test chain call in 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)
但是没用
我认为您正在寻找 receive_message_chain
、https://relishapp.com/rspec/rspec-mocks/docs/working-with-legacy-code/message-chains
他们举的例子是:
allow(Article).to receive_message_chain("recent.published") { [Article.new] }
值得注意的是,使用此方法通常会出现代码异味。
如果您在这里测试接收到消息而不是输出,您可以单独测试第一个方法调用,存根结果,然后测试存根接收第二个方法调用。
我的电话看起来像
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)
但是没用
我认为您正在寻找 receive_message_chain
、https://relishapp.com/rspec/rspec-mocks/docs/working-with-legacy-code/message-chains
他们举的例子是:
allow(Article).to receive_message_chain("recent.published") { [Article.new] }
值得注意的是,使用此方法通常会出现代码异味。
如果您在这里测试接收到消息而不是输出,您可以单独测试第一个方法调用,存根结果,然后测试存根接收第二个方法调用。