Commit e016d8d2 authored by Alishan Ladhani's avatar Alishan Ladhani

Create cop to detect usages of Timecop.travel

parent 4985088f
......@@ -300,6 +300,14 @@ RSpec/TimecopFreeze:
- 'ee/spec/**/*.rb'
- 'qa/spec/**/*.rb'
RSpec/TimecopTravel:
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.travel` usage in specs.
#
# @example
#
# # bad
# Timecop.travel(1.day.ago) { create(:issue) }
#
# # good
# travel_to(1.day.ago) { create(:issue) }
#
class TimecopTravel < RuboCop::Cop::Cop
include MatchRange
MESSAGE = 'Do not use `Timecop.travel`, use `travel_to` instead. ' \
'See https://gitlab.com/gitlab-org/gitlab/-/issues/214432 for more info.'
def_node_matcher :timecop_travel?, <<~PATTERN
(send (const nil? :Timecop) :travel _)
PATTERN
def on_send(node)
return unless timecop_travel?(node)
add_offense(node, location: :expression, message: MESSAGE)
end
def autocorrect(node)
-> (corrector) do
each_match_range(node.source_range, /^(Timecop\.travel)/) do |match_range|
corrector.replace(match_range, 'travel_to')
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_travel'
RSpec.describe RuboCop::Cop::RSpec::TimecopTravel, type: :rubocop do
include CopHelper
subject(:cop) { described_class.new }
context 'when calling Timecop.travel' do
let(:source) do
<<~SRC
Timecop.travel(1.day.ago) { create(:issue) }
SRC
end
let(:corrected_source) do
<<~SRC
travel_to(1.day.ago) { create(:issue) }
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.freeze { create(:issue) }
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