我有以下代碼:如何在rspec 3中存根Date.today.strftime?
def when_to_change
year, month = Date.today.strftime("%Y %m").split(' ').map {|v| v.to_i}
if month < 9
year + 2
else
year + 3
end
end
我嘗試存根在我的規格以下列方式:
it 'when current month at the of a year' do
allow(Date.today).to receive(:strftime).with('%Y %m').and_return('2015 10')
expect(@car.when_to_change).to eq(2018)
end
it 'when current month earlier than september' do
allow(Date.today).to receive(:strftime).with('%Y %m').and_return('2015 07')
expect(@car.when_to_change).to eq(2017)
end
當我嘗試運行規範它看起來並不如此。我究竟做錯了什麼?
我需要Rspec v3.3.2
ANSWER
由於Date.today
回報新對象每個方法調用,這可以通過以下方式進行:
it 'when current month earlier than september' do
allow(Date).to receive(:today).and_return(Date.new(2015, 7, 19))
expect(@car.when_to_change).to eq(2017)
end
謝謝@DmitrySokurenko的說明。
我明白你說什麼,但我還沒有與任何合作方式做上來這個。現在我嘗試了'允許(日期)。收到(:今天).and_return(2015,7,19)',但這不起作用。你能幫我解決嗎? – SuperManEver
創建一些日期:'the_today = Date.new(Date.new(2015,11,19));允許(Date).to接收(今天).and_return(the_today)',然後在它上面存儲所有你需要的東西。 –
爲什麼我需要像'Date.new(Date.new(2015,11,19))'''Date.new''? – SuperManEver