Class: RuboCop::Cop::RSpec::SingleArgumentMessageChain

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/rspec/single_argument_message_chain.rb

Overview

Checks that chains of messages contain more than one element.

Examples:

# bad
allow(foo).to receive_message_chain(:bar).and_return(42)

# good
allow(foo).to receive(:bar).and_return(42)

# also good
allow(foo).to receive(:bar, :baz)
allow(foo).to receive("bar.baz")

Constant Summary collapse

MSG =
'Use `%<recommended>s` instead of calling ' \
'`%<called>s` with a single argument.'
RESTRICT_ON_SEND =
%i[receive_message_chain stub_chain].freeze

Instance Method Summary collapse

Methods inherited from Base

inherited, #on_new_investigation

Methods included from RSpec::Language::NodePattern

#block_pattern, #send_pattern

Methods included from RSpec::Language

#example?, #example_group?, #example_group_with_body?, #hook?, #include?, #let?, #rspec?, #shared_group?, #spec_group?, #subject?

Instance Method Details

#message_chain(node) ⇒ Object


27
28
29
# File 'lib/rubocop/cop/rspec/single_argument_message_chain.rb', line 27

def_node_matcher :message_chain, <<-PATTERN
  (send _ {:receive_message_chain :stub_chain} $_)
PATTERN

#on_send(node) ⇒ Object


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

def on_send(node)
  message_chain(node) do |arg|
    return if valid_usage?(arg)

    method = node.method_name
    msg = format(MSG, recommended: replacement(method), called: method)

    add_offense(node.loc.selector, message: msg) do |corrector|
      autocorrect(corrector, node, method, arg)
    end
  end
end

#single_key_hash?(node) ⇒ Object


32
# File 'lib/rubocop/cop/rspec/single_argument_message_chain.rb', line 32

def_node_matcher :single_key_hash?, '(hash pair)'