Class: RuboCop::Cop::RSpec::ScatteredSetup

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
RangeHelp, FinalEndLocation
Defined in:
lib/rubocop/cop/rspec/scattered_setup.rb

Overview

Checks for setup scattered across multiple hooks in an example group.

Unify before and after hooks when possible. However, around hooks are allowed to be defined multiple times, as unifying them would typically make the code harder to read. Hooks defined in class methods are also ignored.

Examples:

# bad
describe Foo do
  before { setup1 }
  before { setup2 }
end

# good
describe Foo do
  before do
    setup1
    setup2
  end
end

# good
describe Foo do
  around { |example| before1; example.call; after1 }
  around { |example| before2; example.call; after2 }
end

# good
describe Foo do
  before { setup1 }
  def self.setup
    before { setup2 }
  end
end

Constant Summary collapse

MSG =
'Do not define multiple `%<hook_name>s` hooks in the same ' \
'example group (also defined on %<lines>s).'

Instance Method Summary collapse

Methods included from FinalEndLocation

#final_end_location

Methods inherited from Base

inherited, #on_new_investigation

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

#on_block(node) ⇒ Object

rubocop:disable InternalAffairs/NumblockHandler



50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/rubocop/cop/rspec/scattered_setup.rb', line 50

def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
  return unless example_group?(node)

  repeated_hooks(node).each do |occurrences|
    occurrences.each do |occurrence|
      message = message(occurrences, occurrence)
      add_offense(occurrence, message: message) do |corrector|
        autocorrect(corrector, occurrences.first, occurrence)
      end
    end
  end
end