Re: [rspec] Rspec test fails because of miliseconds

286 views
Skip to first unread message

Alex Chaffee

unread,
Jul 5, 2012, 4:00:21 PM7/5/12
to rs...@googlegroups.com
You can use use be_within, like this:

describe "time" do
it "is equal" do
Time.now.should == Time.now #fails
end
it "is close" do
Time.now.should be_within(0.1).of(Time.now)
end
end


On Thu, Jul 5, 2012 at 12:20 PM, Tsvetelina Borisova
<ts.bor...@gmail.com> wrote:
> I have this in one rspec test:
> expected: Thu, 05 Jul 2012 19:07:31 UTC +00:00
> got: Thu, 05 Jul 2012 19:07:31 UTC +00:00
>
> Do you know how to tell to rspec not to consider the miliseconds? Thanks in
> advance : )
>
> --
> You received this message because you are subscribed to the Google Groups
> "rspec" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/rspec/-/UngzRJ7DbbcJ.
> To post to this group, send email to rs...@googlegroups.com.
> To unsubscribe from this group, send email to
> rspec+un...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/rspec?hl=en.



--
Alex Chaffee - al...@stinky.com
http://alexchaffee.com
http://twitter.com/alexch

Antonio Antillon

unread,
Jul 5, 2012, 4:01:07 PM7/5/12
to rs...@googlegroups.com
If you are testing that date/time match... try using the timecop gem, so you can 'freeze' time.

Alex Chaffee

unread,
Jul 5, 2012, 4:45:13 PM7/5/12
to rs...@googlegroups.com
Timecop is fun, but you don't need a whole gem for that. Just use
Time.stub(:now), e.g.

describe "time" do
before do
@fake_time = Time.now
Time.stub(:now) { @fake_time }
end
it "is equal" do
Time.now.should == Time.now # now it passes
end
it "is close" do
Time.now.should be_within(0.1).of(Time.now)
end
end

It's easy to move @fake_time around in the middle of a spec, too, to
simulate time passing or to zap over to e.g. the moment when daylight
savings happens.

- A

Antonio Antillon

unread,
Jul 5, 2012, 4:47:35 PM7/5/12
to rs...@googlegroups.com
@Alex, neat trick :)

Tsvetelina Borisova

unread,
Jul 6, 2012, 1:18:38 AM7/6/12
to rs...@googlegroups.com
@Alex, @Antonio thank you very very much for the fast responses. I will try it and write if it  worked :)
Reply all
Reply to author
Forward
0 new messages