608.620.5104 | info@tenforward.consulting
Psst! We're hiring!

Our inclusive, feminist office is looking to hire for the following positions:

Learn more about the positions and Ten Forward at our careers page, mission and vision page, and about us page. 

Automating timecop gem for testing time-dependent Ruby code

Published April 11, 2016

RSpec is pretty cool. You can define arbitrary flags to toss at the end of a describe, it, context, etc., to run arbitrary code. This is super handy with timecop, a gem to mock Time.now, Date.today, and DateTime.now.

Instead of doing this:

describe '#do_a_thing' do  it 'sets thing_at as now' do    Timecop.freeze    Thing.do_a_thing    expect(Thing.thing_at).to eq Time.now    Timecop.return  endend


Put this in spec/support/timecop.rb:

RSpec.configure do |config|  config.before :each, timecop: :freeze do    Timecop.freeze  end  config.after :each, timecop: :freeze do    Timecop.return  endend


And do:

describe '#do_a_thing' do  it 'sets thing_at as now', timecop: :freeze do    Thing.do_a_thing    expect(Thing.thing_at).to eq Time.now  endend


Doesn't that look nice?

Author details

Staff

@TenFwd