[英]Rspec 3 Rails 4 mock chained method call with parameters
我試圖模擬以下行:
publishers = AdminUser.where(can_publish: true).pluck(:email)
我試過了:
relation = instance_double('AdminUser::ActiveRecord_Relation')
allow(AdminUser).to receive(:where).with(can_publish: true).and_return(relation)
allow(relation).to receive(:pluck).with(:email).and_return(['email', 'email2'])
不幸的是,期望似乎並不匹配。 不會拋出任何錯誤,但不會嘲笑這些方法。
我也試過,然后采取工作。
allow(AdminUser).to receive(:where).with(can_publish: true).and_return([object, object2])
然而,這種期望太生成,當它出現故障where
最匹配的其它where
調用代碼中的高。
我怎么能嘲笑這條線?
雖然您可以按照建議使用receive_message_chain
,但需要考慮這種復雜性,以表明您的類的界面可以更清晰。
RSpec文檔說要考慮使用receive_message_chain代碼氣味 。
一種更好的方法是在AdminUser
上定義一個名為publisher_emails
的類方法,它可以更簡單地存根,並且還提高了代碼的可讀性。
您可以在雙精度上存根方法調用:
require 'rails_helper'
RSpec.describe AdminUser, type: :model do
let(:expected) { ["a@example.com"] }
let(:relation) { double(pluck: expected) }
it "returns the expected value" do
allow(AdminUser).to receive(:where).with(can_publish: true).and_return(relation)
publishers = AdminUser.where(can_publish: true).pluck(:email)
expect(publishers).to eq expected
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.