Class: RuboCop::Cop::RSpec::MessageExpectation

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

Overview

Checks for consistent message expectation style.

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

Examples:

‘EnforcedStyle: allow` (default)


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

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

‘EnforcedStyle: expect`


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

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

Constant Summary collapse

MSG =
'Prefer `%<style>s` for setting message expectations.'
RESTRICT_ON_SEND =
%i[to].freeze

Instance Method Summary collapse

Methods inherited from Base

inherited, #on_new_investigation

Methods included from RSpec::Language::NodePattern

#block_or_numblock_pattern, #block_pattern, #numblock_pattern, #send_pattern

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



35
36
37
# File 'lib/rubocop/cop/rspec/message_expectation.rb', line 35

def_node_matcher :message_expectation, <<~PATTERN
  (send $(send nil? {:expect :allow} ...) :to #receive_message?)
PATTERN

#on_send(node) ⇒ Object



42
43
44
45
46
47
48
49
50
51
# File 'lib/rubocop/cop/rspec/message_expectation.rb', line 42

def on_send(node)
  message_expectation(node) do |match|
    return correct_style_detected if preferred_style?(match)

    message = format(MSG, style: style)
    add_offense(match.loc.selector, message: message) do
      opposite_style_detected
    end
  end
end

#receive_message?(node) ⇒ Object



40
# File 'lib/rubocop/cop/rspec/message_expectation.rb', line 40

def_node_search :receive_message?, '(send nil? :receive ...)'