Give your app time-travel capabilities with Timecop

Ruby on Rails

Sometimes your application’s states and processes evolve with the clock and you need some commands to simulate the passing of time or the arrival of a specific date. Well, like often, in the Rails world there is a gem for that.

Time travel in Rails? Yes. Timecop does exactly that, and boy is it fun to use. Here’s how I quickly made a date picker that allows to modify Time.zone.now and test different processes.

  1. Install Timecop

    bundle add timecop
  2. Create a date selector form. Bonus: add a sprinkle of JS so that the form submits itself each time we pick a date.

    <%= form_with(url: set_date_path, id:'global-date') do |form| %>
      <%= form.date_field :global_date, id:'date-input', placeholder: Time.zone.now.strftime('%d/%m/%Y') %>
    <% end %>
      document.addEventListener("turbo:load", function() {
        const dateInput = document.getElementById("date-input");
        dateInput.addEventListener("change", function() {
  3. Create the set_date method in your ApplicationController using Timecop

    def set_date
      redirect_back(fallback_location: root_path, notice: t("notices.global_date", global_date: Time.zone.now.strftime('%d/%m/%Y')))
  4. Add the route for setting the date

    patch '/set_date', to: 'application#set_date', as: 'set_date'

And voilà, you are now equiped with a tool that H. G. Wells could only dream of.