rubocop / rails-style-guide

A community-driven Ruby on Rails style guide
http://rails.rubystyle.guide
6.48k stars 1.06k forks source link

Add "Prefer `freeze_time` over `travel_to` with an argument of the current time" rule #318

Closed ydah closed 2 years ago

ydah commented 2 years ago

Since there are several ways to indicate the current time, we believe that freeze_time, which can be expressed as simply as possible, should be preferred.

# bad
travel_to(Time.now)
travel_to(DateTime.now)
travel_to(Time.current)
travel_to(Time.zone.now)
travel_to(Time.now.in_time_zone)
travel_to(Time.current.to_time)

# good
freeze_time
pirj commented 2 years ago

It is worth mentioning that freeze_time just delegates to travel_to with a default Time.now (https://github.com/rails/rails/blob/aa3a6c9c1b70e49bef5a2713aae96179debdff3e/activesupport/lib/active_support/testing/time_helpers.rb#L237):

      def freeze_time(&block)
        travel_to Time.now, &block
      end
bbatsov commented 2 years ago

Thanks!