2014-03-25 49 views
1

在我的測試套件中,我有一個失敗的測試。兩個ActiveSupport :: TimeWithZone對象之間的比較失敗

expected[0]['date']來自SomeModel.first.created_at

在調試控制檯,我有以下幾點:

> expected[0]['date'] 
=> Tue, 25 Mar 2014 16:01:45 UTC +00:00 
> res[0]['date'] 
=> Tue, 25 Mar 2014 16:01:45 UTC +00:00 
> res[0]['date'] == expected[0]['date'] 
=> false # wtf 
> res[0]['date'].class 
=> ActiveSupport::TimeWithZone 
> expected[0]['date'].class 
=> ActiveSupport::TimeWithZone 
> 

這怎麼可能?

我試圖重現這個問題(我因子評分也許在TimeWithZone ==操作符檢查的參考,或這樣的事情,但沒有...):

> t1 = Time.zone.at(0) 
=> Thu, 01 Jan 1970 00:00:00 UTC +00:00 
> t2 = Time.zone.parse(t1.to_s) 
=> Thu, 01 Jan 1970 00:00:00 UTC +00:00 
> t1 == t2 
=> true 
> t1.class 
=> ActiveSupport::TimeWithZone 
> t2.class 
=> ActiveSupport::TimeWithZone 

編輯:更多的測試...

> res[0]['date'].eql?(expected[0]['date']) 
=> false 
> res[0]['date'].zone 
=> "UTC" 
> expected[0]['date'].zone 
=> "UTC" 
> expected[0]['date'].getlocal 
=> 2014-03-25 16:01:45 +0000 
> res[0]['date'].getlocal 
=> 2014-03-25 16:01:45 +0000 
> res[0]['date'].hash 
=> -3455877575500291788 
> expected[0]['date'].hash 
=> -3819233736262144515 
> 
> t1.hash 
=> 2279159074362527997 
> t2.hash 
=> 2279159074362527997 

# inspect... 
> expected[0]['date'].inspect 
=> "Tue, 25 Mar 2014 16:39:01 UTC +00:00" 
> res[0]['date'].inspect 
=> "Tue, 25 Mar 2014 16:39:01 UTC +00:00" 

貌似比較是基於哈希對象。爲什麼res和預期有不同的hash es?

+0

什麼是水庫?你有沒有嘗試打印res.inspect和expected.inspect? – vdaubry

+0

@vdaubry添加檢查 –

+0

有這個相同的問題 - 你知道嗎? –

回答

1

回答#1rake db:test:prepare

首先,嘗試下探測試數據庫並重新創建它,然後運行rake db:test:prepare。這在過去爲我解決了這個問題,我知道這有點蹩腳的答案,但它值得一試。

回答#2春+ Rspec的+早該匹配器

如果安裝春天後有這個問題,請結帳這個Github的主題,這可能會導致測試失敗: https://github.com/rails/spring/issues/209

這個問題在我的項目中添加Spring後纔開始發生。 添加gem 'shoulda', require: false和手動添加require 'shoulda/matchers'spec_helper.rb解決的問題

回答#3時空特警

如果仍然遇到問題,簽出時空特警寶石和凍結周圍日期比較時間。 https://github.com/travisjeffery/timecop

+0

看來,錯誤來了frolm比較#to_f 的結果我通過僅使用_aligned_ timestamps與我的測試(例如, 1.day.ago.noon 我的猜測是timecop會做類似的事情。 – lab419