LoginSignup
1
0

RSpecで日時を指定してテストを実行する

Posted at

コード内で、下記のように現在の時間を指定して実行しているコードがあった。

# 現在の日時は営業日かの判定
isWorkDayToday = Time.current.to_date.workday?

この「現在の時間」が例えば⚪︎月⚪︎日というように自身が設定した日時でテストをしたい。

TimeHelpersを使う

今回はRubyのTimeHelpersを使うことにした。

メソッドがいろいろありますが、今回はtravel_toを使うことに。

rails_helper.rbの設定

# 下記の設定を追加
require "active_support/testing/time_helpers"
RSpec.configure do |config|
  config.include ActiveSupport::Testing::TimeHelpers
end

テストを書く

require 'active_support/testing/time_helpers'

RSpec.describe "ExampleNameService" do

    describe '#get_example_function' do
        # 2024年3月18日13時00分を設定
        travel_to Time.new(2024, 3, 18, 13, 0) do
            # この中にテストを記述
        end
    end

end

これでテストを実行したら期待通りの結果になりました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0