Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away