[rspec-users] Date comparisons

s.ross cwdinfo at gmail.com
Mon May 5 12:59:21 EDT 2008


On May 4, 2008, at 11:07 PM, Aslak Hellesøy wrote:

> If your code uses Date#now, always make sure you stub it in your  
> specs. Always.

Yes, but the OP's question was why do two "same" date objects compare  
as different. This is a typical problem with floating-point and  
anything that counts time. I used DateTime.now in my sample code  
below, but certainly I agree that specifying an exact object either by  
stubbing or explicit constant specification is a better idea. There  
will be cases, however, where a strict equality test can't be trusted  
and one must compare something as being within some "close" tolerance.

-s

> On 5. mai. 2008, at 05.42, "s.ross" <cwdinfo at gmail.com> wrote:
>
>> Hi--
>>
>> On May 3, 2008, at 9:17 AM, Joe Van Dyk wrote:
>>
>>> I occasionally get this error:
>>>
>>> 1)
>>> 'A puzzle once featured, should no longer be nominated' FAILED
>>> expected: Sun May 04 09:10:26 -0700 2008,
>>>   got: Sun May 04 09:10:26 -0700 2008 (using ==)
>>> ./spec/models/puzzle_spec.rb:180:
>>>
>>>
>>>
>>> So, the dates looks the same to me.  Any ideas for how to debug?
>>>
>>> Joe
>>
>> I monkeypatched DateTime (aieeeeee!) to get this effect. A custom  
>> matcher is probably a better solution. Here's the monkeypatch:
>>
>> require File.dirname(__FILE__) + '/../spec_helper'
>>
>> class DateTime
>>   def close?(other_date, difference)
>>       (other_date.to_time.to_i - DateTime.now.to_time.to_i).abs <  
>> difference
>>   end
>> end
>>
>> #Delete this context and add some real ones
>> context "should be able to create a project viewer" do
>> fixtures :project_viewers
>>
>> specify "fixtures should load two ProjectViewers" do
>>   pb = ProjectViewer.create(:comments => 'a  
>> comment', :last_viewed_at => DateTime.now)
>>   pb.last_viewed_at.should_be_close(DateTime.now, 100)
>> end
>> end
>>
>>
>> _______________________________________________
>> rspec-users mailing list
>> rspec-users at rubyforge.org
>> http://rubyforge.org/mailman/listinfo/rspec-users
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users



More information about the rspec-users mailing list