Class: RuboCop::Cop::RSpec::MultipleExpectations

Inherits:
RuboCop::Cop
  • Object
show all
Includes:
ConfigurableMax, RSpec::Language, RSpec::SpecOnly
Defined in:
lib/rubocop/cop/rspec/multiple_expectations.rb

Overview

Checks if examples contain too many `expect` calls.

This cop is configurable using the `Max` option and works with `–auto-gen-config`.

Examples:


# bad
describe UserCreator do
  it 'builds a user' do
    expect(user.name).to eq("John")
    expect(user.age).to eq(22)
  end
end

# good
describe UserCreator do
  it 'sets the users name' do
    expect(user.name).to eq("John")
  end

  it 'sets the users age'
    expect(user.age).to eq(22)
  end
end

configuration


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

# not flagged by rubocop
describe UserCreator do
  it 'builds a user' do
    expect(user.name).to eq("John")
    expect(user.age).to eq(22)
  end
end

See Also:

Constant Summary collapse

MSG =
'Too many expectations.'.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?

Instance Method Details

#on_block(node) ⇒ Object


61
62
63
64
65
66
67
68
69
# File 'lib/rubocop/cop/rspec/multiple_expectations.rb', line 61

def on_block(node)
  return unless example?(node) && (expectations = expect(node))

  return if expectations.count <= max_expectations

  self.max = expectations.count

  flag_example(node, expectation_count: expectations.count)
end