簡體   English   中英

如何在 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_chainhttps: receive_message_chain

他們舉的例子是:

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

值得注意的是,使用這種方法通常是代碼異味的征兆。

如果您在這里測試接收的是消息而不是輸出,您可以單獨測試第一個方法調用,存根結果,然后測試存根是否接收第二個方法調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM