Class: RuboCop::Cop::RSpec::NestedGroups

Inherits:
Base
  • Object
show all
Includes:
TopLevelGroup
Defined in:
lib/rubocop/cop/rspec/nested_groups.rb

Overview

Checks for nested example groups.

This cop is configurable using the ‘Max` option and supports `–auto-gen-config`.

Examples:

# bad
context 'when using some feature' do
  let(:some)    { :various }
  let(:feature) { :setup   }

  context 'when user is signed in' do  # flagged by rubocop
    let(:user) do
      UserCreate.call(user_attributes)
    end

    let(:user_attributes) do
      {
        name: 'John',
        age:  22,
        role: role
      }
    end

    context 'when user is an admin' do # flagged by rubocop
      let(:role) { 'admin' }

      it 'blah blah'
      it 'yada yada'
    end
  end
end

# good
context 'using some feature as an admin' do
  let(:some)    { :various }
  let(:feature) { :setup   }

  let(:user) do
    UserCreate.call(
      name: 'John',
      age:  22,
      role: 'admin'
    )
  end

  it 'blah blah'
  it 'yada yada'
end

‘Max: 3` (default)

# bad
describe Foo do
  context 'foo' do
    context 'bar' do
      context 'baz' do # flagged by rubocop
      end
    end
  end
end

‘Max: 2`

# bad
describe Foo do
  context 'foo' do
    context 'bar' do # flagged by rubocop
      context 'baz' do # flagged by rubocop
      end
    end
  end
end

‘AllowedGroups: [] (default)`

describe Foo do # <-- nested groups 1
  context 'foo' do # <-- nested groups 2
    context 'bar' do # <-- nested groups 3
    end
  end
end

‘AllowedGroups: [path]`

describe Foo do # <-- nested groups 1
  path '/foo' do # <-- nested groups 1 (not counted)
    context 'bar' do # <-- nested groups 2
    end
  end
end

Constant Summary collapse

MSG =
'Maximum example group nesting exceeded [%<total>d/%<max>d].'
DEPRECATED_MAX_KEY =
'MaxNesting'
DEPRECATION_WARNING =
"Configuration key `#{DEPRECATED_MAX_KEY}` for #{cop_name} is " \
'deprecated in favor of `Max`. Please use that instead.'

Instance Method Summary collapse

Methods included from TopLevelGroup

#on_new_investigation, #top_level_groups

Methods inherited from Base

inherited, #on_new_investigation

Methods included from RSpec::Language

#example?, #example_group?, #example_group_with_body?, #explicit_rspec?, #hook?, #include?, #let?, #rspec?, #shared_group?, #spec_group?, #subject?

Instance Method Details

#on_top_level_group(node) ⇒ Object



107
108
109
110
111
112
113
114
115
# File 'lib/rubocop/cop/rspec/nested_groups.rb', line 107

def on_top_level_group(node)
  find_nested_example_groups(node) do |example_group, nesting|
    self.max = nesting
    add_offense(
      example_group.send_node,
      message: message(nesting)
    )
  end
end