Class: RuboCop::Cop::RSpec::InstanceSpy

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

Overview

Checks for ‘instance_double` used with `have_received`.

Examples:

# bad
it do
  foo = instance_double(Foo).as_null_object
  expect(foo).to have_received(:bar)
end

# good
it do
  foo = instance_spy(Foo)
  expect(foo).to have_received(:bar)
end

Constant Summary collapse

MSG =
'Use `instance_spy` when you check your double ' \
'with `have_received`.'

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

#have_received_usage(node) ⇒ Object



36
37
38
39
40
41
42
43
# File 'lib/rubocop/cop/rspec/instance_spy.rb', line 36

def_node_search :have_received_usage, <<~PATTERN
  (send
    (send nil? :expect
    (lvar $_)) :to
    (send nil? :have_received
    ...)
  ...)
PATTERN

#null_double(node) ⇒ Object



28
29
30
31
32
33
# File 'lib/rubocop/cop/rspec/instance_spy.rb', line 28

def_node_search :null_double, <<~PATTERN
  (lvasgn $_
    (send
      $(send nil? :instance_double
        ...) :as_null_object))
PATTERN

#on_block(node) ⇒ Object

rubocop:disable InternalAffairs/NumblockHandler



45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/rubocop/cop/rspec/instance_spy.rb', line 45

def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
  return unless example?(node)

  null_double(node) do |var, receiver|
    have_received_usage(node) do |expected|
      next if expected != var

      add_offense(receiver) do |corrector|
        autocorrect(corrector, receiver)
      end
    end
  end
end