Class: RuboCop::Cop::RSpec::MessageSpies

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

Overview

Checks that message expectations are set using spies.

This cop can be configured in your configuration using the ‘EnforcedStyle` option and supports `–auto-gen-config`.

Examples:

‘EnforcedStyle: have_received` (default)


# bad
expect(foo).to receive(:bar)
do_something

# good
allow(foo).to receive(:bar) # or use instance_spy
do_something
expect(foo).to have_received(:bar)

‘EnforcedStyle: receive`


# bad
allow(foo).to receive(:bar)
do_something
expect(foo).to have_received(:bar)

# good
expect(foo).to receive(:bar)
do_something

Constant Summary collapse

MSG_RECEIVE =
'Prefer `receive` for setting message expectations.'
MSG_HAVE_RECEIVED =
'Prefer `have_received` for setting message ' \
'expectations. Setup `%<source>s` as a spy using ' \
'`allow` or `instance_spy`.'
RESTRICT_ON_SEND =
Runners.all

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

#message_expectation(node) ⇒ Object



45
46
47
# File 'lib/rubocop/cop/rspec/message_spies.rb', line 45

def_node_matcher :message_expectation, %(
  (send (send nil? :expect $_) #Runners.all ...)
)

#on_send(node) ⇒ Object



54
55
56
57
58
59
60
61
62
63
# File 'lib/rubocop/cop/rspec/message_spies.rb', line 54

def on_send(node)
  receive_message_matcher(node) do |receiver, message_matcher|
    return correct_style_detected if preferred_style?(message_matcher)

    add_offense(
      message_matcher.loc.selector,
      message: error_message(receiver)
    ) { opposite_style_detected }
  end
end

#receive_message(node) ⇒ Object



50
51
52
# File 'lib/rubocop/cop/rspec/message_spies.rb', line 50

def_node_search :receive_message, %(
  $(send nil? {:receive :have_received} ...)
)