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

Constants inherited from Cop

Cop::DEFAULT_CONFIGURATION, Cop::DEFAULT_PATTERN_RE

Constants included from RSpec::Language

RSpec::Language::ALL, RSpec::Language::RSPEC

Instance Method Summary collapse

Methods inherited from Cop

inherited, #relevant_file?

Instance Method Details

#autocorrect(node) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/rubocop/cop/rspec/instance_spy.rb', line 51

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



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

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

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