Class: RuboCop::Cop::RSpec::ReceiveNever

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

Overview

Prefer not_to receive(...) over receive(...).never.

This cop only flags usage with expect. It ignores allow because allow(...).to receive(...).never is a valid way to ensure a method is not called, while allow(...).not_to receive(...) would have different semantics.

Examples:

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

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

# not flagged by this cop
allow(foo).to receive(:bar).never

Constant Summary collapse

MSG =
'Use `not_to receive` instead of `never`.'
RESTRICT_ON_SEND =
i[never].freeze

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

#expect_to_receive?(node) ⇒ Object



32
33
34
35
36
37
38
39
40
# File 'lib/rubocop/cop/rspec/receive_never.rb', line 32

def_node_matcher :expect_to_receive?, "(send\n  {\n    (send #rspec? {:expect :expect_any_instance_of} ...)\n    (block (send #rspec? :expect) ...)\n    (send nil? :is_expected)\n  }\n  :to ...)\n"

#method_on_stub?(node) ⇒ Object



29
# File 'lib/rubocop/cop/rspec/receive_never.rb', line 29

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

#on_send(node) ⇒ Object



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

def on_send(node)
  return unless node.method?(:never) && method_on_stub?(node)
  return unless used_with_expect?(node)

  add_offense(node.loc.selector) do |corrector|
    autocorrect(corrector, node)
  end
end