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

Inherits:
Base
  • Object
show all
Includes:
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: true

# 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).'

Instance Method Summary collapse

Methods included from TopLevelGroup

#on_new_investigation, #top_level_groups

Methods inherited from Base

inherited, #on_new_investigation

Methods included from RSpec::Language::NodePattern

#block_or_numblock_pattern, #block_pattern, #numblock_pattern, #send_pattern

Methods included from RSpec::Language

#example?, #example_group?, #example_group_with_body?, #explicit_rspec?, #hook?, #include?, #let?, #rspec?, #shared_group?, #spec_group?, #subject?

Instance Method Details

#custom_matcher?(node) ⇒ Object



60
61
62
63
64
65
# File 'lib/rubocop/cop/rspec/instance_variable.rb', line 60

def_node_matcher :custom_matcher?, <<~PATTERN
  (block {
    (send nil? :matcher sym)
    (send (const (const nil? :RSpec) :Matchers) :define sym)
  } ...)
PATTERN

#dynamic_class?(node) ⇒ Object



55
56
57
# File 'lib/rubocop/cop/rspec/instance_variable.rb', line 55

def_node_matcher :dynamic_class?, <<~PATTERN
  (block (send (const nil? :Class) :new ...) ...)
PATTERN

#ivar_assigned?(node) ⇒ Object



71
# File 'lib/rubocop/cop/rspec/instance_variable.rb', line 71

def_node_search :ivar_assigned?, '(ivasgn % ...)'

#ivar_usage(node) ⇒ Object



68
# File 'lib/rubocop/cop/rspec/instance_variable.rb', line 68

def_node_search :ivar_usage, '$(ivar $_)'

#on_top_level_group(node) ⇒ Object



73
74
75
76
77
78
79
80
# File 'lib/rubocop/cop/rspec/instance_variable.rb', line 73

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