问题描述
我在ruby模型中有一个方法调用,如下所示:
I have a method call in a ruby model that looks like the following:
Contentful::PartnerCampaign.find_by(vanityUrl: referral_source).load.first
在模型的spec.rb文件中,我试图模拟该调用并通过传入参数来获取值.但是我很难弄清楚调用它的正确方法.
Within the models spec.rb file, I'm trying to mock that call and get a value by passing in a param. But I'm having trouble figuring out the correct way of calling it.
在我的spec.rb文件的顶部,
At the top of my spec.rb file I have:
let(:first_double) {
double("Contentful::Model", fields {:promotion_type => "Promotion 1"})
}
在describe块中,我尝试了以下操作:
Within the describe block I've tried the following:
expect(Contentful::PartnerCampaign).to receive_message_chain(:find_by, :load, :first).
and_return(first_double)
expect(Contentful::PartnerCampaign).to receive_message_chain(:find_by, :load, :first).with(vanityUrl: 'test_promo_path').
and_return(first_double)
expect(Contentful::PartnerCampaign).to receive_message_chain(:find_by => vanityUrl: 'test_promo_path', :load, :first).
and_return(first_double)
您可能会猜到,这些都不起作用.有人知道做这种事情的正确方法吗?甚至有可能吗?
As you can probably guess, none of these are working. Does anyone know the correct way to do this sort of thing? Is it even possible?
推荐答案
一般来讲,我不希望使用存根链,因为它们通常表示您违反了《得墨meter耳法律》 .但是,如果需要的话,这就是我模拟该序列的方式:
Generally speaking, I prefer not to use stub chains, as they are often a sign that you are violating the Law of Demeter. But, if I had to, this is how I would mock that sequence:
let(:vanity_url) { 'https://vanity.url' }
let(:partner_campaigns) { double('partner_campaigns') }
let(:loaded_partner_campaigns) { double('loaded_partner_campaigns') }
let(:partner_campaign) do
double("Contentful::Model", fields {:promotion_type => "Promotion 1"}
end
before do
allow(Contentful::PartnerCampaign)
.to receive(:find_by)
.with(vanity_url: vanity_url)
.and_return(partner_campaigns)
allow(partner_campaigns)
.to receive(:load)
.and_return(loaded_partner_campaigns)
allow(loaded_partner_campaigns)
.to receive(:first)
.and_return(partner_campaign)
end
这篇关于在第一个方法采用参数的情况下,如何使用Rspec“期望"方法链?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!