LoginSignup
0
1

More than 5 years have passed since last update.

テストコードの Timecop.freeze の戻し忘れで Devise に関係するテストが落ちてた

Last updated at Posted at 2018-10-31

何が起きたか

テスト中に Devise.gem の active_for_authentication? (source)がなぜか true になってしまう問題が発生。ログインできないのに認証されているように振る舞い、テストが落ちた。

原因

active_for_authentication? が呼んでる confirmation_period_valid? (source)が変な動きをしていることがわかった。

device/lib/devise/models/confirmable.rb
def confirmation_period_valid?
  self.class.allow_unconfirmed_access_for.nil? || (confirmation_sent_at && confirmation_sent_at.utc >= self.class.allow_unconfirmed_access_for.ago)
end

デフォルトだと allow_unconfirmed_access_for が 0 seconds になっててかならず false がかえるんだけど、 Timecop.freeze することで confirmation_sent_at.utc >= self.class.allow_unconfirmed_access_for.ago が 0 seconds でも true を返すようになってた。

対策

Timecop.freeze したあとは Timecop.return する

spec_helper.rb
RSpec.configure do |config|
  config.after(:all) do
    Timecop.return
  end
end

って書いちゃっても良いと思う。もしくは safe_mode をオンにしてブロックなしで使えなくする。

cf: https://github.com/travisjeffery/timecop

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