0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

時間に関わるspec

Last updated at Posted at 2021-05-12

目的

特定の時間になるかを確認するためにspecを書きたい
どのように書けば良いか分からず調べた

travel_toとは

ActiveSupport :: Testing :: TimeHelpersのメソッドの一つです。

変更したい日時を渡すと、Time.now、Date.today、DateTime.nowで返される
日時を変更することができます。

コードイメージ

spec/models/○○○_spec.rb
Spec.describe Task, type: :model do
  it 'is whether now time' do
    travel_to('2019-05-26 23:00'.to_time) do
      expect(Time.zone.now).to eq(Time.new(2019, 5, 26, 23, 0, 0))
    end
    after do
     travel_back
    end
  end
end

指定した時間に、時間を止められます

it 'puts date and time' do
  travel_to Time.zone.local(2020, 03, 16) do
    pp Date.today   # -> Mon, 16 Mar 2020
    pp Time.now     # -> 2020-03-15 15:00:00 +0000
    pp DateTime.now # -> Mon, 16 Mar 2020 00:00:00 +0900
  end
end

Rails 5.2系から下記の記載は必要なくなったようです。
情報ありがとうございます!

時間を止めてしまうとそれ以降のspecの時間も止まってしまうため、
下記の記述が必要になります。

    after do
     travel_back
    end

参考URL

https://qiita.com/mightysosuke/items/72f764fc237422b423b0
https://fuqda.hatenablog.com/entry/2019/03/04/223012

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?