Skip to content

Add RSpecRails/Timecop cop #48

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Master (Unreleased)

- Add a cop that makes `Timecop` illegal, in favour of `ActiveSupport::Testing::TimeHelpers`. ([@sambostock])

## 2.30.0 (2024-06-12)

- Fix an runtime error for rubocop-rspec +3.0. ([@bquorning])
Expand Down Expand Up @@ -79,6 +81,7 @@
[@paydaylight]: https://github.com/paydaylight
[@pirj]: https://github.com/pirj
[@r7kamura]: https://github.com/r7kamura
[@sambostock]: https://github.com/sambostock
[@splattael]: https://github.com/splattael
[@tmaier]: https://github.com/tmaier
[@ydah]: https://github.com/ydah
7 changes: 7 additions & 0 deletions config/default.yml
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,13 @@ RSpecRails/NegationBeValid:
VersionChanged: '2.29'
Reference: https://www.rubydoc.info/gems/rubocop-rspec_rails/RuboCop/Cop/RSpecRails/NegationBeValid

RSpecRails/Timecop:
Description: Enforces use of ActiveSupport TimeHelpers instead of Timecop.
Enabled: pending
VersionAdded: "<<next>>"
SafeAutoCorrect: false
Reference: https://www.rubydoc.info/gems/rubocop-rspec_rails/RuboCop/Cop/RSpecRails/Timecop

RSpecRails/TravelAround:
Description: Prefer to travel in `before` rather than `around`.
Enabled: pending
Expand Down
1 change: 1 addition & 0 deletions docs/modules/ROOT/pages/cops.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
* xref:cops_rspecrails.adoc#rspecrailsinferredspectype[RSpecRails/InferredSpecType]
* xref:cops_rspecrails.adoc#rspecrailsminitestassertions[RSpecRails/MinitestAssertions]
* xref:cops_rspecrails.adoc#rspecrailsnegationbevalid[RSpecRails/NegationBeValid]
* xref:cops_rspecrails.adoc#rspecrailstimecop[RSpecRails/Timecop]
* xref:cops_rspecrails.adoc#rspecrailstravelaround[RSpecRails/TravelAround]

// END_COP_LIST
110 changes: 110 additions & 0 deletions docs/modules/ROOT/pages/cops_rspecrails.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,116 @@ expect(foo).to be_invalid.or be_even

* https://www.rubydoc.info/gems/rubocop-rspec_rails/RuboCop/Cop/RSpecRails/NegationBeValid

== RSpecRails/Timecop

|===
| Enabled by default | Safe | Supports autocorrection | Version Added | Version Changed

| Pending
| Yes
| Always (Unsafe)
| <<next>>
| -
|===

Enforces use of ActiveSupport TimeHelpers instead of Timecop.

## Migration
`Timecop.freeze` should be replaced with `freeze_time` when used
without arguments. Where a `duration` has been passed to `freeze`, it
should be replaced with `travel`. Likewise, where a `time` has been
passed to `freeze`, it should be replaced with `travel_to`.

`Timecop.scale` should be replaced by explicitly calling `travel` or
`travel_to` with the expected `durations` or `times`, respectively,
rather than relying on allowing time to continue to flow.

`Timecop.return` should be replaced with `travel_back`, when used
without a block. `travel_back` accepts a block starting with Rails 6.1.
For earlier Rails, where `return` is used with a block, it should
be replaced by explicitly calling `freeze_time` with a block, and
passing the `time` to temporarily return to.

`Timecop.travel` should be replaced by `travel` or `travel_to` when
passed a `duration` or `time`, respectively. As with `Timecop.scale`,
rather than relying on time continuing to flow, it should be travelled
to explicitly.

All other usages of `Timecop` are similarly disallowed.

## RSpec Caveats

Note that if using RSpec, `TimeHelpers` are not included by default,
and must be manually included by updating `rails_helper` accordingly:

```ruby
RSpec.configure do |config|
config.include ActiveSupport::Testing::TimeHelpers
end
```

Moreover, because `TimeHelpers` relies on Minitest teardown hooks,
`rails_helper` must be required (instead of `spec_helper`), or a
similar adapter layer must be in effect.

=== Examples

[source,ruby]
----
# bad
Timecop

# bad
Timecop.freeze
Timecop.freeze(duration)
Timecop.freeze(time)

# good
freeze_time
travel(duration)
travel_to(time)

# bad
Timecop.freeze { assert true }
Timecop.freeze(duration) { assert true }
Timecop.freeze(time) { assert true }

# good
freeze_time { assert true }
travel(duration) { assert true }
travel_to(time) { assert true }

# bad
Timecop.travel(duration)
Timecop.travel(time)

# good
travel(duration)
travel_to(time)

# bad
Timecop.return
Timecop.return { assert true }

# good
travel_back
travel_back { assert true }

# bad
Timecop.scale(factor)
Timecop.scale(factor) { assert true }

# good
travel(duration)
travel_to(time)
travel(duration) { assert true }
travel_to(time) { assert true }
----

=== References

* https://www.rubydoc.info/gems/rubocop-rspec_rails/RuboCop/Cop/RSpecRails/Timecop

== RSpecRails/TravelAround

|===
Expand Down
209 changes: 209 additions & 0 deletions lib/rubocop/cop/rspec_rails/timecop.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
# frozen_string_literal: true

module RuboCop
module Cop
module RSpecRails
# Enforces use of ActiveSupport TimeHelpers instead of Timecop.
#
# ## Migration
# `Timecop.freeze` should be replaced with `freeze_time` when used
# without arguments. Where a `duration` has been passed to `freeze`, it
# should be replaced with `travel`. Likewise, where a `time` has been
# passed to `freeze`, it should be replaced with `travel_to`.
#
# `Timecop.scale` should be replaced by explicitly calling `travel` or
# `travel_to` with the expected `durations` or `times`, respectively,
# rather than relying on allowing time to continue to flow.
#
# `Timecop.return` should be replaced with `travel_back`, when used
# without a block. `travel_back` accepts a block starting with Rails 6.1.
# For earlier Rails, where `return` is used with a block, it should
# be replaced by explicitly calling `freeze_time` with a block, and
# passing the `time` to temporarily return to.
#
# `Timecop.travel` should be replaced by `travel` or `travel_to` when
# passed a `duration` or `time`, respectively. As with `Timecop.scale`,
# rather than relying on time continuing to flow, it should be travelled
# to explicitly.
#
# All other usages of `Timecop` are similarly disallowed.
#
# ## RSpec Caveats
#
# Note that if using RSpec, `TimeHelpers` are not included by default,
# and must be manually included by updating `rails_helper` accordingly:
#
# ```ruby
# RSpec.configure do |config|
# config.include ActiveSupport::Testing::TimeHelpers
# end
# ```
#
# Moreover, because `TimeHelpers` relies on Minitest teardown hooks,
# `rails_helper` must be required (instead of `spec_helper`), or a
# similar adapter layer must be in effect.
Comment on lines +42 to +44
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do not understand this part of the comments. I think what is required is that #travel_back is called in an after block in the spec configuration (be it rails_helper or spec_helper or other).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right. It's not that TimeHelpers need to be required from rails_helper, or rails_helper should be required.
Minitest teardown hooks will only run for Rails example groups, those where specific metadata is set (:model, :controller etc), manually in each spec, or with define_derived_metadata.

This note should be changed accordingly.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On a slightly different note, the RSpec maintainers plan to sunset setting this metadata automatically with define_derived_metadata sometimes in the future, I think our users will either:

  1. define derived metadata on their own
  2. start setting metadata explicitly

We don't know for sure, so relying on explicitly set metadata to skip or proceed with this inspection is not a viable option.

Maybe rspec-rails should wrap TimeHelpers module with their own that would inject after { reset_time_helpers! }? We could then write a cop that suggests using this module instead.

#
# @example
# # bad
# Timecop
#
# # bad
# Timecop.freeze
# Timecop.freeze(duration)
# Timecop.freeze(time)
#
# # good
# freeze_time
# travel(duration)
# travel_to(time)
#
# # bad
# Timecop.freeze { assert true }
# Timecop.freeze(duration) { assert true }
# Timecop.freeze(time) { assert true }
#
# # good
# freeze_time { assert true }
# travel(duration) { assert true }
# travel_to(time) { assert true }
#
# # bad
# Timecop.travel(duration)
# Timecop.travel(time)
#
# # good
# travel(duration)
# travel_to(time)
#
# # bad
# Timecop.return
# Timecop.return { assert true }
#
# # good
# travel_back
# travel_back { assert true }
#
# # bad
# Timecop.scale(factor)
# Timecop.scale(factor) { assert true }
#
# # good
# travel(duration)
# travel_to(time)
# travel(duration) { assert true }
# travel_to(time) { assert true }
class Timecop < ::RuboCop::Cop::Base
extend AutoCorrector

FREEZE_MESSAGE = 'Use `%<replacement>s` instead of `Timecop.freeze`'
FREEZE_WITH_ARGUMENTS_MESSAGE =
'Use `travel` or `travel_to` instead of `Timecop.freeze`'
RETURN_MESSAGE = 'Use `%<replacement>s` instead of `Timecop.return`'
FLOW_ADDENDUM =
'If you need time to keep flowing, simulate it by travelling again.'
TRAVEL_MESSAGE =
'Use `travel` or `travel_to` instead of `Timecop.travel`. ' \
"#{FLOW_ADDENDUM}"
SCALE_MESSAGE =
'Use `travel` or `travel_to` instead of `Timecop.scale`. ' \
"#{FLOW_ADDENDUM}"
MSG = 'Use `ActiveSupport::Testing::TimeHelpers` instead of `Timecop`'

# @!method timecop_const?(node)
def_node_matcher :timecop_const?, <<~PATTERN
(const {nil? cbase} :Timecop)
PATTERN

# @!method timecop_send(node)
def_node_matcher :timecop_send, <<~PATTERN
(send
#timecop_const? ${:freeze :return :scale :travel}
$...
)
PATTERN

def on_const(node)
return unless timecop_const?(node)

timecop_send(node.parent) do |message, arguments|
return on_timecop_send(node.parent, message, arguments)
end

add_offense(node)
end

private

def on_timecop_send(node, message, arguments)
case message
when :freeze then on_timecop_freeze(node, arguments)
when :return then on_timecop_return(node, arguments)
when :scale then on_timecop_scale(node, arguments)
when :travel then on_timecop_travel(node, arguments)
else add_offense(node)
end
end

def on_timecop_freeze(node, arguments)
if arguments.empty?
message =
format(FREEZE_MESSAGE, replacement: preferred_freeze_replacement)
add_offense(node, message: message) do |corrector|
autocorrect_freeze(corrector, node, arguments)
end
else
add_offense(node, message: FREEZE_WITH_ARGUMENTS_MESSAGE)
end
end

def on_timecop_return(node, arguments)
message =
format(RETURN_MESSAGE, replacement: 'travel_back')
add_offense(node, message: message) do |corrector|
autocorrect_return(corrector, node, arguments)
end
end

def on_timecop_scale(node, _arguments)
add_offense(node, message: SCALE_MESSAGE)
end

def on_timecop_travel(node, _arguments)
add_offense(node, message: TRAVEL_MESSAGE)
end

def autocorrect_freeze(corrector, node, arguments)
return unless arguments.empty?

corrector.replace(receiver_and_message_range(node),
preferred_freeze_replacement)
end

def autocorrect_return(corrector, node, _arguments)
return if given_block?(node) && !supports_return_with_block?

corrector.replace(receiver_and_message_range(node), 'travel_back')
end

def given_block?(node)
node.parent&.block_type? && node.parent.send_node == node
end

# travel_back { ... } was introduced in Rails 6.1
def supports_return_with_block?
target_rails_version >= 6.1
end

def receiver_and_message_range(node)
node.source_range.with(end_pos: node.location.selector.end_pos)
end

def preferred_freeze_replacement
return 'travel_to(Time.now)' if target_rails_version < 5.2

'freeze_time'
end
end
end
end
end
1 change: 1 addition & 0 deletions lib/rubocop/cop/rspec_rails_cops.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@
require_relative 'rspec_rails/inferred_spec_type'
require_relative 'rspec_rails/minitest_assertions'
require_relative 'rspec_rails/negation_be_valid'
require_relative 'rspec_rails/timecop'
require_relative 'rspec_rails/travel_around'
Loading