2015-11-19 32 views
0

我有以下代碼:如何在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的說明。

回答

1

Date.today總是返回新的對象。首先將today存根。

我的意思是:

>> Date.today.object_id 
=> 70175652485620 
>> Date.today.object_id 
=> 70175652610440 

所以,當你調用today接下來的時間,這是一個不同的對象。

因此,要麼將Date.today存根返回某個固定日期,要麼將代碼更改爲使用類似於SomeHelper.today的東西,這將始終在測試環境中返回相同的日期。

+0

我明白你說什麼,但我還沒有與任何合作方式做上來這個。現在我嘗試了'允許(日期)。收到(:今天).and_return(2015,7,19)',但這不起作用。你能幫我解決嗎? – SuperManEver

+0

創建一些日期:'the_today = Date.new(Date.new(2015,11,19));允許(Date).to接收(今天).and_return(the_today)',然後在它上面存儲所有你需要的東西。 –

+0

爲什麼我需要像'Date.new(Date.new(2015,11,19))'''Date.new''? – SuperManEver

3

我認爲timecop將正是你所需要的。