Class: RuboCop::Cop::RSpec::HookArgument

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

Overview

Checks the arguments passed to ‘before`, `around`, and `after`.

This cop checks for consistent style when specifying RSpec hooks which run for each example. There are three supported styles: “implicit”, “each”, and “example.” All styles have the same behavior.

Examples:

when configuration is ‘EnforcedStyle: implicit`

# bad
before(:each) do
  # ...
end

# bad
before(:example) do
  # ...
end

# good
before do
  # ...
end

when configuration is ‘EnforcedStyle: each`

# bad
before(:example) do
  # ...
end

# good
before do
  # ...
end

# good
before(:each) do
  # ...
end

when configuration is ‘EnforcedStyle: example`

# bad
before(:each) do
  # ...
end

# bad
before do
  # ...
end

# good
before(:example) do
  # ...
end

Constant Summary collapse

IMPLICIT_MSG =
'Omit the default `%<scope>p` ' \
'argument for RSpec hooks.'
EXPLICIT_MSG =
'Use `%<scope>p` for RSpec hooks.'
HOOKS =
Hooks::ALL.node_pattern_union.freeze

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

#autocorrect(node) ⇒ Object



89
90
91
92
93
94
95
# File 'lib/rubocop/cop/rspec/hook_argument.rb', line 89

def autocorrect(node)
  scope = implicit_style? ? '' : "(#{style.inspect})"

  lambda do |corrector|
    corrector.replace(argument_range(node), scope)
  end
end

#on_block(node) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/rubocop/cop/rspec/hook_argument.rb', line 75

def on_block(node)
  hook(node) do |method_send, scope_name|
    return correct_style_detected if scope_name.equal?(style)
    return check_implicit(method_send) unless scope_name

    style_detected(scope_name)
    add_offense(
      method_send,
      location: :expression,
      message: explicit_message(scope_name)
    )
  end
end