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

Inherits:
Cop
  • Object
show all
Includes:
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

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].'.freeze
DEPRECATED_MAX_KEY =
'MaxNesting'.freeze
DEPRECATION_WARNING =
"Configuration key `#{DEPRECATED_MAX_KEY}` for #{cop_name} is " \
'deprecated in favor of `Max`. Please use that instead.'.freeze

Constants inherited from Cop

Cop::DEFAULT_CONFIGURATION, Cop::DEFAULT_PATTERN_RE

Constants included from RSpec::Language

RSpec::Language::ALL

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



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

def on_top_level_describe(node, _args)
  find_nested_contexts(node.parent) do |context, nesting|
    add_offense(
      context.children.first,
      location: :expression,
      message: message(nesting)
    )
  end
end