Skip to content

Commit

Permalink
Code review. Count nesting recursively
Browse files Browse the repository at this point in the history
  • Loading branch information
andrykonchin committed Jul 1, 2020
1 parent 397ecb3 commit 5475110
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 12 deletions.
18 changes: 6 additions & 12 deletions lib/rubocop/cop/rspec/nested_groups.rb
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,6 @@ class NestedGroups < Cop
"Configuration key `#{DEPRECATED_MAX_KEY}` for #{cop_name} is " \
'deprecated in favor of `Max`. Please use that instead.'

def_node_search :find_example_groups, ExampleGroups::ALL.block_pattern
def_node_matcher :example_group?, ExampleGroups::ALL.block_pattern

def on_top_level_describe(node, _args)
find_nested_example_groups(node.parent) do |example_group, nesting|
self.max = nesting
Expand All @@ -112,17 +109,14 @@ def on_top_level_describe(node, _args)

private

def find_nested_example_groups(node)
find_example_groups(node) do |example_group|
nesting = nesting_count(example_group)
def find_nested_example_groups(node, nesting: 1, &block)
yield node, nesting if example_group?(node) && nesting > max_nesting

yield(example_group, nesting) if nesting > max_nesting
end
end
next_nesting = example_group?(node) ? nesting + 1 : nesting

def nesting_count(node)
count = node.each_ancestor(:block).count { |n| example_group?(n) }
count + 1
node.each_child_node do |child|
find_nested_example_groups(child, nesting: next_nesting, &block)
end
end

def message(nesting)
Expand Down
16 changes: 16 additions & 0 deletions spec/rubocop/cop/rspec/nested_groups_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,20 @@ class MyThingy
).to_stderr
end
end

it 'counts nesting correctly when non-spec nesting' do
expect_offense(<<-RUBY)
describe MyClass do
context 'when foo' do
context 'when bar' do
[].each do |i|
context 'when baz' do
^^^^^^^^^^^^^^^^^^ Maximum example group nesting exceeded [4/3].
end
end
end
end
end
RUBY
end
end

0 comments on commit 5475110

Please sign in to comment.