コード日進月歩

しんくうの技術的な小話、メモ、つれづれ、など

RailsでTimecopを使わず現在時間をずらすRSpecを書く

実はTimecopはいらなくなったという話題の実践編

環境

rails (5.1.5)
rspec (3.7.0)

やり方

helperに追記

rails_helper.rbのお好みのところに追加

RSpec.configure do |config|
  # 中略
  config.include ActiveSupport::Testing::TimeHelpers

end

使い方

travel_to で囲む

context "現在時刻かどうかは" do
  it "こんな感じでテストをかく" do
    travel_to('2018-3-10 8:00'.to_time) do
      expect(Time.zone.now).to eq(Time.new(2018, 3, 10, 8, 0, 0))
    end
  end
end

around をつかうと、複数のitにも対応できるのでそちらも便利。

context "現在時刻かどうか確認" do
  around do |e|
    travel_to('2018-3-10 8:00'.to_time) {e.run}
  end
  it "日付が同じ" do
    expect(Time.zone.now).to eq(Time.new(2018, 3, 10, 8, 0, 0))
  end
  it "異なる日付である" do
    expect(Time.zone.now).not_to eq(Time.new(2018, 4, 10, 8, 0, 0))
  end
end

参考サイト