Skip to content

Commit

Permalink
Merge pull request #946 from andrykonchin/optimize-performance-instan…
Browse files Browse the repository at this point in the history
…ce-variable

Performance. RSpec/InstanceVariable
  • Loading branch information
Darhazer committed Jun 30, 2020
2 parents c51c544 + dae7025 commit 7e2d6dc
Show file tree
Hide file tree
Showing 2 changed files with 17 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
14 changes: 14 additions & 0 deletions spec/rubocop/cop/rspec/instance_variable_spec.rb
Expand Up @@ -152,5 +152,19 @@ def serialize
end
RUBY
end

it 'flags an instance variable when it is also assigned ' \
'in a 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 7e2d6dc

Please sign in to comment.