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

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
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:

‘EnforcedStyle: implicit` (default)

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

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

# good
before do
  # ...
end

‘EnforcedStyle: each`

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

# bad
before do
  # ...
end

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

‘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.'

Instance Method Summary collapse

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 Also known as: on_numblock



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

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)
    msg = explicit_message(scope_name)
    add_offense(method_send, message: msg) do |corrector|
      autocorrect(corrector, node, method_send)
    end
  end
end

#scoped_hook(node) ⇒ Object



69
70
71
# File 'lib/rubocop/cop/rspec/hook_argument.rb', line 69

def_node_matcher :scoped_hook, <<~PATTERN
  ({block numblock} $(send _ #Hooks.all (sym ${:each :example})) ...)
PATTERN

#unscoped_hook(node) ⇒ Object



74
75
76
# File 'lib/rubocop/cop/rspec/hook_argument.rb', line 74

def_node_matcher :unscoped_hook, <<~PATTERN
  ({block numblock} $(send _ #Hooks.all) ...)
PATTERN