class RuboCop::Cop::RSpec::MessageSpies

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`.

@example `EnforcedStyle: have_received`

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

# good
expect(foo).to have_received(:bar)

@example `EnforcedStyle: receive`

# bad
expect(foo).to have_received(:bar)

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

Constants

MSG_HAVE_RECEIVED
MSG_RECEIVE
SUPPORTED_STYLES

Public Instance Methods

on_send(node) click to toggle source
# File lib/rubocop/cop/rspec/message_spies.rb, line 47
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,
      location: :selector,
      message: error_message(receiver)
    ) { opposite_style_detected }
  end
end

Private Instance Methods

error_message(receiver) click to toggle source
# File lib/rubocop/cop/rspec/message_spies.rb, line 71
def error_message(receiver)
  case style
  when :receive
    MSG_RECEIVE
  when :have_received
    MSG_HAVE_RECEIVED % receiver.source
  end
end
preferred_style?(expectation) click to toggle source
# File lib/rubocop/cop/rspec/message_spies.rb, line 67
def preferred_style?(expectation)
  expectation.method_name.equal?(style)
end
receive_message_matcher(node) { |receiver, match| ... } click to toggle source
# File lib/rubocop/cop/rspec/message_spies.rb, line 61
def receive_message_matcher(node)
  return unless (receiver = message_expectation(node))

  receive_message(node) { |match| yield(receiver, match) }
end