Skip to content

Commit

Permalink
RSpec/InstanceVariable. Optimize #on_block callback
Browse files Browse the repository at this point in the history
  • Loading branch information
andrykonchin committed Jun 28, 2020
1 parent fad3387 commit 5c51e4d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
10 changes: 3 additions & 7 deletions lib/rubocop/cop/rspec/instance_variable.rb
Expand Up @@ -47,13 +47,11 @@ module RSpec
# end
#
class InstanceVariable < Cop
include RuboCop::RSpec::TopLevelGroup

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

EXAMPLE_GROUP_METHODS = ExampleGroups::ALL + SharedGroups::ALL

def_node_matcher :spec_group?, EXAMPLE_GROUP_METHODS.block_pattern

def_node_matcher :dynamic_class?, <<-PATTERN
(block (send (const nil? :Class) :new ...) ...)
PATTERN
Expand All @@ -69,9 +67,7 @@ class InstanceVariable < Cop

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

def on_block(node)
return unless spec_group?(node)

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)
Expand Down
13 changes: 13 additions & 0 deletions spec/rubocop/cop/rspec/instance_variable_spec.rb
Expand Up @@ -152,5 +152,18 @@ def serialize
end
RUBY
end

it 'flags an instance variable when it is also assigned in sibling example group' do
expect_offense(<<-RUBY)
describe MyClass do
context 'foo' do
before { @foo = [] }
end
it { expect(@foo).to be_empty }
^^^^ Avoid instance variables – use let, a method call, or a local variable (if possible).
end
RUBY
end
end
end

0 comments on commit 5c51e4d

Please sign in to comment.