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

Inherits:
Cop
  • Object
show all
Includes:
ConfigurableMax, RSpec::TopLevelDescribe
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.'

Constants inherited from Cop

Cop::DEFAULT_CONFIGURATION, Cop::DEFAULT_PATTERN_RE

Constants included from RSpec::Language

RSpec::Language::ALL, RSpec::Language::RSPEC

Instance Method Summary collapse

Methods included from RSpec::TopLevelDescribe

#on_send

Methods inherited from Cop

inherited, #relevant_file?

Instance Method Details

#on_top_level_describe(node, _args) ⇒ Object


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

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