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

Inherits:
Cop
  • Object
show all
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`.'.freeze
EXAMPLES =
Examples::ALL.node_pattern_union.freeze

Constants inherited from Cop

Cop::DEFAULT_CONFIGURATION

Constants included from RSpec::Language

RSpec::Language::ALL

Instance Method Summary collapse

Methods inherited from Cop

inherited, #relevant_file?

Instance Method Details

#autocorrect(node) ⇒ Object


55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/rubocop/cop/rspec/instance_spy.rb', line 55

def autocorrect(node)
  lambda do |corrector|
    replacement = 'instance_spy'
    corrector.replace(node.loc.selector, replacement)

    double_source_map = node.parent.loc
    as_null_object_range = double_source_map
      .dot
      .join(double_source_map.selector)
    corrector.remove(as_null_object_range)
  end
end

#on_block(node) ⇒ Object


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

def on_block(node)
  return unless example?(node)

  null_double(node) do |var, receiver|
    have_received_usage(node) do |expected|
      add_offense(receiver, :expression) if expected == var
    end
  end
end