class RuboCop::Cop::RSpec::MultipleExpectations
Checks if examples contain too many `expect` calls.
@see betterspecs.org/#single Single expectation test
This cop is configurable using the `Max` option and works with `–auto-gen-config`.
@example
# 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
@example 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
Constants
- MSG
Public Instance Methods
on_block(node)
click to toggle source
# File lib/rubocop/cop/rspec/multiple_expectations.rb, line 63 def on_block(node) return unless example?(node) return if example_with_aggregated_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
Private Instance Methods
aggregated_failures_by_default?()
click to toggle source
# File lib/rubocop/cop/rspec/multiple_expectations.rb, line 114 def aggregated_failures_by_default? cop_config.fetch('AggregateFailuresByDefault', false) end
example_with_aggregated_failures?(node)
click to toggle source
# File lib/rubocop/cop/rspec/multiple_expectations.rb, line 79 def example_with_aggregated_failures?(node) example = node.send_node (aggregated_failures_by_default? || with_aggregated_failures?(example)) && !disabled_aggregated_failures?(example) end
find_expectation(node) { || ... }
click to toggle source
# File lib/rubocop/cop/rspec/multiple_expectations.rb, line 87 def find_expectation(node, &block) yield if expect?(node) || aggregate_failures?(node) # do not search inside of aggregate_failures block return if aggregate_failures?(node) node.each_child_node do |child| find_expectation(child, &block) end end
flag_example(node, expectation_count:)
click to toggle source
# File lib/rubocop/cop/rspec/multiple_expectations.rb, line 98 def flag_example(node, expectation_count:) add_offense( node.send_node, location: :expression, message: format( MSG, total: expectation_count, max: max_expectations ) ) end
max_expectations()
click to toggle source
# File lib/rubocop/cop/rspec/multiple_expectations.rb, line 110 def max_expectations Integer(cop_config.fetch('Max', 1)) end