Class: RuboCop::Cop::RSpec::Rails::TravelAround

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/rspec/rails/travel_around.rb

Overview

Prefer to travel in ‘before` rather than `around`.

Examples:

# bad
around do |example|
  freeze_time do
    example.run
  end
end

# good
before { freeze_time }

Constant Summary collapse

MSG =
'Prefer to travel in `before` rather than `around`.'
TRAVEL_METHOD_NAMES =
%i[
  freeze_time
  travel
  travel_to
].to_set.freeze

Instance Method Summary collapse

Methods inherited from Base

inherited, #on_new_investigation

Methods included from RSpec::Language::NodePattern

#block_or_numblock_pattern, #block_pattern, #numblock_pattern, #send_pattern

Methods included from RSpec::Language

#example?, #example_group?, #example_group_with_body?, #explicit_rspec?, #hook?, #include?, #let?, #rspec?, #shared_group?, #spec_group?, #subject?

Instance Method Details

#extract_run_in_travel(node) ⇒ Object



39
40
41
42
43
44
45
# File 'lib/rubocop/cop/rspec/rails/travel_around.rb', line 39

def_node_matcher :extract_run_in_travel, <<~PATTERN
  (block
    $(send nil? TRAVEL_METHOD_NAMES ...)
    (args ...)
    (send _ :run)
  )
PATTERN

#match_around_each?(node) ⇒ Object



48
49
50
51
52
53
# File 'lib/rubocop/cop/rspec/rails/travel_around.rb', line 48

def_node_matcher :match_around_each?, <<~PATTERN
  (block
    (send _ :around (sym :each)?)
    ...
  )
PATTERN

#on_block(node) ⇒ Object Also known as: on_numblock



55
56
57
58
59
60
61
62
63
64
65
# File 'lib/rubocop/cop/rspec/rails/travel_around.rb', line 55

def on_block(node)
  run_node = extract_run_in_travel(node)
  return unless run_node

  around_node = extract_surrounding_around_block(run_node)
  return unless around_node

  add_offense(node) do |corrector|
    autocorrect(corrector, node, run_node, around_node)
  end
end