Class: RuboCop::Cop::RSpec::AnyInstance

Inherits:
RuboCop::Cop show all
Includes:
RSpec::SpecOnly
Defined in:
lib/rubocop/cop/rspec/any_instance.rb

Overview

Check that instances are not being stubbed globally.

Prefer instance doubles over stubbing any instance of a class

Examples:

# bad
describe MyClass do
  before { allow_any_instance_of(MyClass).to receive(:foo) }
end

# good
describe MyClass do
  let(:my_instance) { instance_double(MyClass) }

  before do
    allow(MyClass).to receive(:new).and_return(my_instance)
    allow(my_instance).to receive(:foo)
  end
end

Constant Summary collapse

MESSAGE =
'Avoid stubbing using `%{method}`'.freeze
ANY_INSTANCE_METHODS =
[
  :any_instance,
  :allow_any_instance_of,
  :expect_any_instance_of
].freeze

Constants included from RSpec::SpecOnly

RSpec::SpecOnly::DEFAULT_CONFIGURATION

Instance Method Summary collapse

Methods included from RSpec::SpecOnly

#relevant_file?

Instance Method Details

#on_send(node) ⇒ Object



34
35
36
37
38
39
# File 'lib/rubocop/cop/rspec/any_instance.rb', line 34

def on_send(node)
  _receiver, method_name, *_args = *node
  return unless ANY_INSTANCE_METHODS.include?(method_name)

  add_offense(node, :expression, MESSAGE % { method: method_name })
end