Class: RuboCop::Cop::RSpec::InstanceVariable

Inherits:
RuboCop::Cop show all
Defined in:
lib/rubocop/cop/rspec/instance_variable.rb

Overview

When you have to assign a variable instead of using an instance variable, use let.

Examples:

# bad
describe MyClass do
  before { @foo = [] }
  it { expect(@foo).to be_empty }
end

# good
describe MyClass do
  let(:foo) { [] }
  it { expect(foo).to be_empty }
end

Constant Summary collapse

MESSAGE =
'Use `let` instead of an instance variable'.freeze
EXAMPLE_GROUP_METHODS =
[
  :example_group, :describe, :context, :xdescribe, :xcontext,
  :fdescribe, :fcontext, :shared_examples, :shared_context,
  :share_examples_for, :shared_examples_for, :feature
].freeze

Instance Method Summary collapse

Instance Method Details

#on_block(node) ⇒ Object



30
31
32
33
34
# File 'lib/rubocop/cop/rspec/instance_variable.rb', line 30

def on_block(node)
  method, _args, _body = *node
  _receiver, method_name, _object = *method
  @in_spec = true if EXAMPLE_GROUP_METHODS.include?(method_name)
end

#on_ivar(node) ⇒ Object



36
37
38
# File 'lib/rubocop/cop/rspec/instance_variable.rb', line 36

def on_ivar(node)
  add_offense(node, :expression, MESSAGE) if @in_spec
end