Traveling in time

 

Lear how you can travel in time in your tests with Rail's travel_to helper. We are going to create a view helper and we will follow Test Driven Development.

Ok, I will be honest with you. I don't always write tests first and also I usually don't test helpers. But this was a nice opportunity how to describe travel_to's functionality.

Code samples

# app/views/layouts/application.html.erb

&copy; <%= copyright_years(2016) %> Patrik Bóna
# test/helpers/copyright_helper_test.rb

require "test_helper"

class CopyrightHelperTest < ActionView::TestCase
  test "starting years is the same as current year" do
    travel_to "2016-01-02" do
      assert_equal "2016", copyright_years(2016)
    end
  end

  test "starting year is not the same as current year" do
    travel_to "2017-01-02" do
      assert_equal "2016 - 2017", copyright_years(2016)
    end
  end
end
# app/helpers/copyright_helper.rb

module CopyrightHelper
  def copyright_years(starting_year)
    current_year = Time.current.year

    if starting_year == current_year
      starting_year.to_s
    else
      "#{starting_year} - #{current_year}"
    end
  end
end

If you want to use travel_to with RSpec, then you have to include ActiveSupport::Testing::TimeHelpers in your specs, or in your spec_helper.rb.

# spec/spec_helper.rb

RSpec.configure do |config|
  config.include ActiveSupport::Testing::TimeHelpers
end

Other alternative is to use the timecop gem.

Links