search
LoginSignup
6

More than 5 years have passed since last update.

posted at

updated at

ActiveSupport だけでも Timecop のように時間を固定できるが、使いにくい

Timecop gem を入れなくても ActiveSupport があれば travel_to メソッドで時間を固定できます。
しかし Timecop と比べてみると、ActiveSupport の方は、ブロックを抜けた後、なぜか一気に元の時間まで戻ってしまうため、全体で時間を固定して一部で一時的に時間を変更するような使い方をするテストが書きづらいです。

require "active_support/time"

# ActiveSupport
require "active_support/testing/time_helpers"
include ActiveSupport::Testing::TimeHelpers
Time.current                    # => 2015-05-22 22:21:09 +0900
travel_to("1900-01-01") do
  Time.current                  # => 1900-01-01 00:00:00 +0900
  travel_to("1900-01-02") do
    Time.current                # => 1900-01-02 00:00:00 +0900
    travel_to("1900-01-03") do
      Time.current              # => 1900-01-03 00:00:00 +0900
    end
    Time.current                # => 2015-05-22 22:21:09 +0900
  end
  Time.current                  # => 2015-05-22 22:21:09 +0900
end
Time.current                    # => 2015-05-22 22:21:09 +0900

# Timecop
require "timecop"
Time.current                    # => 2015-05-22 22:21:09 +0900
Timecop.freeze("1900-01-01") do
  Time.current                  # => 1900-01-01 00:00:00 +0900
  Timecop.freeze("1900-01-02") do
    Time.current                # => 1900-01-02 00:00:00 +0900
    Timecop.freeze("1900-01-03") do
      Time.current              # => 1900-01-03 00:00:00 +0900
    end
    Time.current                # => 1900-01-02 00:00:00 +0900
  end
  Time.current                  # => 1900-01-01 00:00:00 +0900
end
Time.current                    # => 2015-05-22 22:21:09 +0900

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
What you can do with signing up
6