Skip to content

Commit

Permalink
RSpec/NestedGroups Optimize #on_top_level_describe callback
Browse files Browse the repository at this point in the history
  • Loading branch information
andrykonchin committed Jun 28, 2020
1 parent fad3387 commit 12a45e7
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions lib/rubocop/cop/rspec/nested_groups.rb
Expand Up @@ -98,6 +98,7 @@ class NestedGroups < Cop
'deprecated in favor of `Max`. Please use that instead.'

def_node_search :find_contexts, ExampleGroups::ALL.block_pattern
def_node_matcher :context?, ExampleGroups::ALL.block_pattern

def on_top_level_describe(node, _args)
find_nested_contexts(node.parent) do |context, nesting|
Expand All @@ -111,16 +112,19 @@ def on_top_level_describe(node, _args)

private

def find_nested_contexts(node, nesting: 1, &block)
def find_nested_contexts(node)
find_contexts(node) do |nested_context|
yield(nested_context, nesting) if nesting > max_nesting
nesting = context_nesting_count(nested_context)

nested_context.each_child_node do |child|
find_nested_contexts(child, nesting: nesting + 1, &block)
end
yield(nested_context, nesting) if nesting > max_nesting
end
end

def context_nesting_count(node)
parents = node.ancestors.select { |a| context?(a) }
parents.count + 1
end

def message(nesting)
format(MSG, total: nesting, max: max_nesting)
end
Expand Down

0 comments on commit 12a45e7

Please sign in to comment.