Commit 5579c05e authored by Mayra Cabrera's avatar Mayra Cabrera

Merge branch 'ali/add-rubocop-rule-for-timecop' into 'master'

Add a cop to detect usages of Timecop.freeze

See merge request gitlab-org/gitlab!39656
parents 5edbb420 cc471766
......@@ -282,6 +282,14 @@ Cop/ActiveRecordAssociationReload:
Gitlab/AvoidFeatureGet:
Enabled: true
RSpec/TimecopFreeze:
Enabled: false
AutoCorrect: true
Include:
- 'spec/**/*.rb'
- 'ee/spec/**/*.rb'
- 'qa/spec/**/*.rb'
Naming/PredicateName:
Enabled: true
Exclude:
......
# frozen_string_literal: true
module RuboCop
module Cop
module RSpec
# This cop checks for `Timecop.freeze` usage in specs.
#
# @example
#
# # bad
# Timecop.freeze(Time.current) { example.run }
#
# # good
# freeze_time(Time.current) { example.run }
#
class TimecopFreeze < RuboCop::Cop::Cop
include MatchRange
MESSAGE = 'Do not use `Timecop.freeze`, use `freeze_time` instead. ' \
'See https://gitlab.com/gitlab-org/gitlab/-/issues/214432 for more info.'
def_node_matcher :timecop_freeze?, <<~PATTERN
(send (const nil? :Timecop) :freeze ?_)
PATTERN
def on_send(node)
return unless timecop_freeze?(node)
add_offense(node, location: :expression, message: MESSAGE)
end
def autocorrect(node)
-> (corrector) do
each_match_range(node.source_range, /^(Timecop\.freeze)/) do |match_range|
corrector.replace(match_range, 'freeze_time')
end
end
end
end
end
end
end
# frozen_string_literal: true
require 'fast_spec_helper'
require 'rubocop'
require 'rubocop/rspec/support'
require_relative '../../../../rubocop/cop/rspec/timecop_freeze'
RSpec.describe RuboCop::Cop::RSpec::TimecopFreeze, type: :rubocop do
include CopHelper
subject(:cop) { described_class.new }
context 'when calling Timecop.freeze' do
let(:source) do
<<~SRC
Timecop.freeze(Time.current) { example.run }
SRC
end
let(:corrected_source) do
<<~SRC
freeze_time(Time.current) { example.run }
SRC
end
it 'registers an offence' do
inspect_source(source)
expect(cop.offenses.size).to eq(1)
end
it 'can autocorrect the source' do
expect(autocorrect_source(source)).to eq(corrected_source)
end
end
context 'when calling a different method on Timecop' do
let(:source) do
<<~SRC
Timecop.travel(Time.current)
SRC
end
it 'does not register an offence' do
inspect_source(source)
expect(cop.offenses).to be_empty
end
end
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment