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

Inherits:
Cop
  • Object
show all
Defined in:
lib/rubocop/cop/rspec/scattered_setup.rb

Overview

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

Unify ‘before`, `after`, and `around` hooks when possible.

Examples:

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

# good
describe Foo do
  before do
    setup1
    setup2
  end
end

Constant Summary collapse

MSG =
'Do not define multiple hooks in the same example group.'

Constants inherited from Cop

Cop::DEFAULT_CONFIGURATION, Cop::DEFAULT_PATTERN_RE

Constants included from RSpec::Language

RSpec::Language::ALL, RSpec::Language::RSPEC

Instance Method Summary collapse

Methods inherited from Cop

inherited, #relevant_file?

Instance Method Details

#analyzable_hooks(node) ⇒ Object



36
37
38
39
40
41
42
43
44
45
# File 'lib/rubocop/cop/rspec/scattered_setup.rb', line 36

def analyzable_hooks(node)
  RuboCop::RSpec::ExampleGroup.new(node)
    .hooks
    .select { |hook| hook.knowable_scope? && hook.valid_scope? }
    .group_by { |hook| [hook.name, hook.scope] }
    .values
    .reject(&:one?)
    .flatten
    .map(&:to_node)
end

#on_block(node) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/rubocop/cop/rspec/scattered_setup.rb', line 28

def on_block(node)
  return unless example_group?(node)

  analyzable_hooks(node).each do |repeated_hook|
    add_offense(repeated_hook, location: :expression)
  end
end