2014-02-17 42 views
1

我想下面的代碼在RSpec中比較兩個時間對象:RSpec的預期等於(Time對象)返回true,得到了假

describe '#current_shift_datetime' do 
    subject { WipStack.current_shift_datetime } 
    it "To be a Time object" do 
    expect(subject).to be_kind_of(Time) 
    end 
    it "To return current shift datetime" do 
    # Trying to figure out why they are not equal 
    puts subject.in_time_zone.round 
    puts 0.day.ago.midnight.in_time_zone.round 

    # Problematic code here --> 
    expect(subject.in_time_zone.round).to be_equal(0.day.ago.midnight.in_time_zone.round) 
    # End of problematic code 
    end 
end 

我看過一對夫婦在網上有關rspec時間比較的事情,其中​​一個解釋毫秒(因此輪)的問題和另一個頁面談論stub,但後來我結束了An error occurred in an after hook SystemStackError: stack level too deep

測試的輸出中是:

1) WipStack#current_shift_datetime To return current shift datetime 
    Failure/Error: expect(subject.in_time_zone.round).to be_equal(0.day.ago.midnight.in_time_zone.round) 
    expected equal?(Mon, 17 Feb 2014 00:00:00 CST -06:00) to return true, got false 

的所說輸出:

#current_shift_datetime 
    To be a Time object 
    2014-02-17 00:00:00 -0600 
    2014-02-17 00:00:00 -0600 
    To return current shift datetime (FAILED - 1) 

更新:

這裏是current_shift_datetime方法:

def WipStack.current_shift_datetime(scope = nil) 
    shifts = WipStack.get_shifts(scope) 
    current_shift = (Time.zone.now - 1.day).strftime("%m/%d/%Y")+" "+shifts.last 
    current_time = Time.zone.now.strftime("%H:%M") 
    shifts.each do |shift| 
    if current_time > shift 
     current_shift = Time.zone.now.strftime("%m/%d/%Y")+" "+shift 
    end 
    end 
    Time.zone.parse(current_shift) 
end 
+0

讓我們來看看'current_shift_datetime'方法 – CharlesJHardy

+0

感謝@CharlesJHardy這裏是代碼 –

回答

2

您可以嘗試比較字符串表示法,而不是直接比較時區(並細微區別),因爲這是您在控制檯中檢查的內容。

根據您在應用中如何使用此時區,這應該足以說明它們基本上是同一時間。

expect(subject.in_time_zone.round.to_s).to eq(0.day.ago.midnight.in_time_zone.round.to_s) 

你也許可以刪除.round如果你想爲好。

編輯

試着改變你的代碼,以便之間存在着什麼是印刷的,什麼是比較沒有什麼區別:

it "To return current shift datetime" do 
    a = subject.in_time_zone.round.to_s 
    b = 0.day.ago.midnight.in_time_zone.round.to_s 

    puts a 
    puts b 

    expect(a).to eq(b) 
end 
+0

現在我很困惑,我真的認爲這會解決它,但對於原因,我不明白這一點給我的同樣的錯誤... 1)WipStack#previous_shift_datetime返回上一班日期時間 預期失敗/錯誤:期望(subject.to_s).to be_equal(1.day.ago.midnight.to_s) 期望等於?(「2014-02 -16 00:00:00 -0600「)返回true,得到虛假的' –

+0

根據放置它​​是相同的字符串'成爲時間對象 2014-02-16 00:00:00 -0600 2014-02- 16 00:00:00 -0600' –

+0

嘿,謝謝你的合作我發現了答案:) –

0

我固定它得益於tyler!似乎be_equal實際上是試圖看看兩個對象是否相同(在比較字符串時,測試失敗時出現註釋),將be_equal改爲eq使測試通過!

it "To return current shift datetime" do 
    #pending 
    puts subject.in_time_zone.round.to_s 
    puts 0.day.ago.midnight.in_time_zone.round.to_s 
    expect(subject.in_time_zone.round.to_s).to eq(0.day.ago.midnight.in_time_zone.round.to_s) 
end 
+1

請接受答案,而不是複製它 – bjhaid

相關問題