Stubbing Time.now

There have been several times recently when I’ve needed to test that the time set in a particular method is Time.now. However, this isn’t particularly (or at all) accurate.

s = Story.new
s.access_it
s.last_accessed_at.should == Time.now

This all reads fine, but our test will always take time to run. So the current time when then the method is called is not likely to be same as the current time that it is being tested at and if it is then you are extremely lucky. Hence the following.

Time.stub!(:now).and_return(Time.now)
s = Story.new
s.access_it
s.last_accessed_at.should == Time.now