カレンダーの現在日時を変更する

前回の続きです。
ブログのスクリーンショット用にカレンダーの現在時刻を変更しました。
ちょい足ししたコードをご紹介します。

timecop Gem で現在時刻を変更することが多いと思いますが、今回は Rails のテスト用の現在時刻を変更する機能を使いたいと思います。

active_support/testing/time_helpers を require する。
ActiveSupport::Testing::TimeHelpers を include する。
現在時刻(今日)を travel_to で 2026-01-02 にする。

app/controllers/home_controller.rb

require "active_support/testing/time_helpers"

class HomeController < ApplicationController
  include ActiveSupport::Testing::TimeHelpers

  def index
    travel_to Date.parse("2026-01-02")
    start_date = params.fetch(:start_date, Date.today).to_date
    @meetings = Meeting.where(start_time: start_date.beginning_of_month.beginning_of_week..start_date.end_of_month.end_of_week)
  end
end

以上です。



▼この記事がいいね!と思ったらブックマークお願いします
このエントリーをはてなブックマークに追加