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

Inherits:
Base
  • Object
show all
Includes:
ConfigurableMax, 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

# better
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

configuration


# .rubocop.yml
# RSpec/NestedGroups:
#   Max: 2

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

  context 'when user is signed in' do
    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

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::NodePattern

#block_pattern, #send_pattern

Methods included from RSpec::Language

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

Instance Method Details

#on_top_level_group(node) ⇒ Object


100
101
102
103
104
105
106
107
108
# File 'lib/rubocop/cop/rspec/nested_groups.rb', line 100

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