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

Inherits:
Cop
  • Object
show all
Includes:
ConfigurableEnforcedStyle, RSpec::Language, RSpec::SpecOnly
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 `%p` argument for RSpec hooks.'.freeze
EXPLICIT_MSG =
'Use `%p` for RSpec hooks.'.freeze
HOOKS =
"{#{Hooks::ALL.to_node_pattern}}".freeze

Constants included from RSpec::Language

RSpec::Language::ALL

Constants included from RSpec::SpecOnly

RSpec::SpecOnly::DEFAULT_CONFIGURATION

Instance Method Summary collapse

Methods included from RSpec::SpecOnly

#relevant_file?

Instance Method Details

#autocorrect(node) ⇒ Object



86
87
88
89
90
91
92
93
# File 'lib/rubocop/cop/rspec/hook_argument.rb', line 86

def autocorrect(node)
  scope = "(#{style.inspect})" unless implicit_style?
  hook  = "#{node.method_name}#{scope}"

  lambda do |corrector|
    corrector.replace(node.loc.expression, hook)
  end
end

#on_block(node) ⇒ Object



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

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, :expression, explicit_message(scope_name))
  end
end