“...I've been working since 2008 with Ruby / Ruby on Rails, love a bit of Elixir / Phoenix and learning Rust. I also poke through other people's code and make PRs for OpenSource Ruby projects that sometimes make it. Currently working for InPay...”

Rob Lacey (contact@robl.me)
Senior Software Engineer, Brighton, UK

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