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

Inherits:
Cop
  • Object
show all
Includes:
ConfigurableMax
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' do
    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 =
'Example has too many expectations [%<total>d/%<max>d].'

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 inherited from Cop

inherited, #relevant_file?

Instance Method Details

#on_block(node) ⇒ Object


72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/rubocop/cop/rspec/multiple_expectations.rb', line 72

def on_block(node)
  return unless example?(node)

  return if example_with_aggregate_failures?(node)

  expectations_count = to_enum(:find_expectation, node).count

  return if expectations_count <= max_expectations

  self.max = expectations_count

  flag_example(node, expectation_count: expectations_count)
end