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.
Install Timecop
bundle add timecop
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 %> <script> document.addEventListener("turbo:load", function() { const dateInput = document.getElementById("date-input"); dateInput.addEventListener("change", function() { document.getElementById("global-date").submit(); }); }); </script>
Create the set_date method in your ApplicationController using Timecop
def set_date Timecop.travel(params[:global_date]) redirect_back(fallback_location: root_path, notice: t("notices.global_date", global_date: Time.zone.now.strftime('%d/%m/%Y'))) end
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.