Class: RuboCop::Cop::RSpec::ReceiveMessages

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

Overview

Checks for multiple messages stubbed on the same object.

Examples:

# bad
before do
  allow(Service).to receive(:foo).and_return(bar)
  allow(Service).to receive(:baz).and_return(qux)
end

# good
before do
  allow(Service).to receive_messages(foo: bar, baz: qux)
end

# good - ignore same message
before do
  allow(Service).to receive(:foo).and_return(bar)
  allow(Service).to receive(:foo).and_return(qux)
end

Constant Summary collapse

MSG =
'Use `receive_messages` instead of multiple stubs on lines ' \
'%<loc>s.'

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

#allow_argument(node) ⇒ Object



44
45
46
# File 'lib/rubocop/cop/rspec/receive_messages.rb', line 44

def_node_matcher :allow_argument, <<~PATTERN
  (send (send nil? :allow $_ ...) ...)
PATTERN

#allow_receive_message?(node) ⇒ Object



39
40
41
# File 'lib/rubocop/cop/rspec/receive_messages.rb', line 39

def_node_matcher :allow_receive_message?, <<~PATTERN
  (send (send nil? :allow ...) :to (send (send nil? :receive (sym _)) :and_return !#heredoc_or_splat?))
PATTERN

#on_begin(node) ⇒ Object



63
64
65
66
67
68
69
# File 'lib/rubocop/cop/rspec/receive_messages.rb', line 63

def on_begin(node)
  repeated_receive_message(node).each do |item, repeated_lines, args|
    next if repeated_lines.empty?

    register_offense(item, repeated_lines, args)
  end
end

#receive_and_return_argument(node) ⇒ Object



59
60
61
# File 'lib/rubocop/cop/rspec/receive_messages.rb', line 59

def_node_matcher :receive_and_return_argument, <<~PATTERN
  (send (send nil? :allow ...) :to (send (send nil? :receive (sym $_)) :and_return $_))
PATTERN

#receive_arg(node) ⇒ Object



54
55
56
# File 'lib/rubocop/cop/rspec/receive_messages.rb', line 54

def_node_search :receive_arg, <<~PATTERN
  (send (send nil? :receive $_) ...)
PATTERN

#receive_node(node) ⇒ Object



49
50
51
# File 'lib/rubocop/cop/rspec/receive_messages.rb', line 49

def_node_search :receive_node, <<~PATTERN
  $(send (send nil? :receive ...) ...)
PATTERN