Class: RuboCop::Cop::RSpec::MultipleMemoizedHelpers

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

Overview

Checks if example groups contain too many let and subject calls.

This cop is configurable using the Max option and the AllowSubject which will configure the cop to only register offenses on calls to let and not calls to subject.

Examples:

# bad
describe MyClass do
  let(:foo) { [] }
  let(:bar) { [] }
  let!(:baz) { [] }
  let(:qux) { [] }
  let(:quux) { [] }
  let(:quuz) { {} }
end

describe MyClass do
  let(:foo) { [] }
  let(:bar) { [] }
  let!(:baz) { [] }

  context 'when stuff' do
    let(:qux) { [] }
    let(:quux) { [] }
    let(:quuz) { {} }
  end
end

# good
describe MyClass do
  let(:bar) { [] }
  let!(:baz) { [] }
  let(:qux) { [] }
  let(:quux) { [] }
  let(:quuz) { {} }
end

describe MyClass do
  context 'when stuff' do
    let(:foo) { [] }
    let(:bar) { [] }
    let!(:booger) { [] }
  end

  context 'when other stuff' do
    let(:qux) { [] }
    let(:quux) { [] }
    let(:quuz) { {} }
  end
end

when disabling AllowSubject configuration

# rubocop.yml
# RSpec/MultipleMemoizedHelpers:
#   AllowSubject: false

# bad - `subject` counts towards memoized helpers
describe MyClass do
  subject { {} }
  let(:foo) { [] }
  let(:bar) { [] }
  let!(:baz) { [] }
  let(:qux) { [] }
  let(:quux) { [] }
end

with Max configuration

# rubocop.yml
# RSpec/MultipleMemoizedHelpers:
#   Max: 1

# bad
describe MyClass do
  let(:foo) { [] }
  let(:bar) { [] }
end

Constant Summary collapse

MSG =
'Example group has too many memoized helpers [%<count>d/%<max>d]'

Constants included from Variable

Variable::Helpers, Variable::Subjects

Instance Method Summary collapse

Methods included from Variable

#variable_definition?

Methods inherited from Base

inherited

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_block(node) ⇒ Object

rubocop:disable InternalAffairs/NumblockHandler



91
92
93
94
95
96
97
98
99
100
# File 'lib/rubocop/cop/rspec/multiple_memoized_helpers.rb', line 91

def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
  return unless spec_group?(node)

  count = all_helpers(node).uniq.count

  return if count <= max

  self.max = count
  add_offense(node, message: format(MSG, count: count, max: max))
end

#on_new_investigationObject



102
103
104
105
# File 'lib/rubocop/cop/rspec/multiple_memoized_helpers.rb', line 102

def on_new_investigation
  super
  @example_group_memoized_helpers = {}
end