RajSharma RajSharma - 2 months ago 15
Ruby Question

How to mock offset method using RSPEC?

Please don't downvote. I am new to RPSEC.

I've a method named

_apply_offset
. It contents are as follows-

def _apply_offset(campaign_params)

if campaign_params['adsets'].length <= 0
return campaign_params
end


## offset
offset = Facebook::Currency.new(current_advertiser).offset
puts "offset = "+offset.to_s
campaign_params['adsets'].each do |adset|
# lifetime_budget,daily_budget
if adset['budget']['value']
adset['budget']['value'] = (adset['budget']['value'] * offset).round
end

next if(adset['bid']['method'] == 'OCPM')
if adset['bid']['value']
adset['bid']['value'] = (adset['bid']['value'] * offset).round
end
end

return campaign_params


end
As you can see in the above code I am calling
Facebook::Currency.new(current_advertiser).offset


I want the value of this function to return 100.

Offset function looks like this-

def offset
currency = M_FACEBOOK_CURRENCIES['JPY']
currency = M_FACEBOOK_CURRENCIES[@facebook_information.currency] unless @facebook_information.currency.nil?
return currency[:offset]
end


my RSPEC code looks like below-

describe "#_apply_offset" do
let(:current_user) { User.find(10) }
let(:current_advertiser) { Advertiser.find(4) }
let(:campaign_params) {
{
'adsets' => []
}
}

before do
allow(controller).to receive(:current_user).and_return(current_user)
allow(controller).to receive(:current_advertiser).and_return(current_advertiser)
end

subject { controller.send(:_apply_offset, campaign_params) }
context "CPC/CPM params" do
let(:campaign_params) {
{
'adsets' => [
{
'budget' => {
'value' => 1000
},
'bid' => {
'value' => 1000
}
},
]
}
}
describe "budget value" do
it "offset budget value and round" do
expect(subject['adsets'][0]['budget']['value']).to eq(1000)
end
end
describe "bid value" do
it "offset bid value and round" do
expect(subject['adsets'][0]['bid']['value']).to eq(1000)
end
end
end
context "OCPM params" do
let(:campaign_params) {
{
'adsets' => [
{
'budget' => {
'value' => 1000
},
'bid' => {
'method' => 'OCPM',
'value' => ''
}
},
]
}
}
describe "method = OCPM" do
it "expects round method doesn't execute" do
expect(subject['adsets'][0]['bid']['value']).to eq('')
end
end
end


end

In the before hook i tried
allow(Facebook::Currency).to receive(:offset).and return)(100)
but it doesn't work.

Please help.

Answer

You actually do not want Facebook::Currency to receive the offset message, but its instances :)

allow_any_instance_of(Facebook::Currency).
  to receive(:offset).and_return(100)