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

Inherits:
Cop
  • Object
show all
Includes:
RSpec::TopLevelGroup
Defined in:
lib/rubocop/cop/rspec/instance_variable.rb

Overview

Checks for instance variable usage in specs.

This cop can be configured with the option `AssignmentOnly` which will configure the cop to only register offenses on instance variable usage if the instance variable is also assigned within the spec

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

with AssignmentOnly configuration


# rubocop.yml
# RSpec/InstanceVariable:
#   AssignmentOnly: false

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

# allowed
describe MyClass do
  it { expect(@foo).to be_empty }
end

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

Constant Summary collapse

MSG =
'Avoid instance variables – use let, ' \
'a method call, or a local variable (if possible).'

Constants included from RSpec::Language

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

Constants inherited from Cop

Cop::DEFAULT_CONFIGURATION, Cop::DEFAULT_PATTERN_RE

Instance Method Summary collapse

Methods included from RSpec::TopLevelGroup

#on_block

Methods inherited from Cop

inherited, #relevant_file?

Instance Method Details

#on_top_level_group(node) ⇒ Object


70
71
72
73
74
75
76
77
# File 'lib/rubocop/cop/rspec/instance_variable.rb', line 70

def on_top_level_group(node)
  ivar_usage(node) do |ivar, name|
    next if valid_usage?(ivar)
    next if assignment_only? && !ivar_assigned?(node, name)

    add_offense(ivar)
  end
end