简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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