Reputation:
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
Upvotes: 1
Views: 181
Reputation: 6445
I think you're looking for receive_message_chain
, https://relishapp.com/rspec/rspec-mocks/docs/working-with-legacy-code/message-chains
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.
Upvotes: 2