class RuboCop::Cop::RSpec::InstanceVariable
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
@example
# 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
@example 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
Constants
- MSG
Public Instance Methods
Source
# 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
Private Instance Methods
Source
# File lib/rubocop/cop/rspec/instance_variable.rb, line 90 def assignment_only? cop_config['AssignmentOnly'] end
Source
# File lib/rubocop/cop/rspec/instance_variable.rb, line 84 def valid_usage?(node) node.each_ancestor(:block).any? do |block| dynamic_class?(block) || custom_matcher?(block) end end