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

Inherits:
RuboCop::Cop show all
Includes:
RSpec::Language, RSpec::SpecOnly, RSpec::TopLevelDescribe
Defined in:
lib/rubocop/cop/rspec/nested_groups.rb

Overview

Checks for nested example groups.

This cop is configurable using the ‘MaxNesting` 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:
  MaxNesting: 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'.freeze

Constants included from RSpec::SpecOnly

RSpec::SpecOnly::DEFAULT_CONFIGURATION

Constants included from RSpec::Language

RSpec::Language::ALL

Instance Method Summary collapse

Methods included from RSpec::SpecOnly

#relevant_file?

Methods included from RSpec::TopLevelDescribe

#on_send

Instance Method Details

#on_block(node) ⇒ Object



98
99
100
101
102
103
104
105
# File 'lib/rubocop/cop/rspec/nested_groups.rb', line 98

def on_block(node)
  describe, = described_constant(node)
  return unless describe

  find_nested_contexts(node) do |context|
    add_offense(context.children.first, :expression)
  end
end