Skip to content

Commit 85b0399

Browse files
committed
RSpec/NestedGroups Optimize #on_top_level_describe callback
1 parent fad3387 commit 85b0399

File tree

2 files changed

+25
-10
lines changed

2 files changed

+25
-10
lines changed

lib/rubocop/cop/rspec/nested_groups.rb

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -97,27 +97,26 @@ class NestedGroups < Cop
9797
"Configuration key `#{DEPRECATED_MAX_KEY}` for #{cop_name} is " \
9898
'deprecated in favor of `Max`. Please use that instead.'
9999

100-
def_node_search :find_contexts, ExampleGroups::ALL.block_pattern
101-
102100
def on_top_level_describe(node, _args)
103-
find_nested_contexts(node.parent) do |context, nesting|
101+
find_nested_example_groups(node.parent) do |example_group, nesting|
104102
self.max = nesting
105103
add_offense(
106-
context.send_node,
104+
example_group.send_node,
107105
message: message(nesting)
108106
)
109107
end
110108
end
111109

112110
private
113111

114-
def find_nested_contexts(node, nesting: 1, &block)
115-
find_contexts(node) do |nested_context|
116-
yield(nested_context, nesting) if nesting > max_nesting
112+
def find_nested_example_groups(node, nesting: 1, &block)
113+
example_group = example_group?(node)
114+
yield node, nesting if example_group && nesting > max_nesting
115+
116+
next_nesting = example_group ? nesting + 1 : nesting
117117

118-
nested_context.each_child_node do |child|
119-
find_nested_contexts(child, nesting: nesting + 1, &block)
120-
end
118+
node.each_child_node(:block, :begin) do |child|
119+
find_nested_example_groups(child, nesting: next_nesting, &block)
121120
end
122121
end
123122

spec/rubocop/cop/rspec/nested_groups_spec.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,4 +76,20 @@ class MyThingy
7676
).to_stderr
7777
end
7878
end
79+
80+
it 'counts nesting correctly when non-spec nesting' do
81+
expect_offense(<<-RUBY)
82+
describe MyClass do
83+
context 'when foo' do
84+
context 'when bar' do
85+
[].each do |i|
86+
context 'when baz' do
87+
^^^^^^^^^^^^^^^^^^ Maximum example group nesting exceeded [4/3].
88+
end
89+
end
90+
end
91+
end
92+
end
93+
RUBY
94+
end
7995
end

0 commit comments

Comments
 (0)