Class: RuboCop::Cop::RSpec::ReceiveCounts

Inherits:
Cop
  • Object
show all
Defined in:
lib/rubocop/cop/rspec/receive_counts.rb

Overview

Check for ‘once` and `twice` receive counts matchers usage.

Examples:


# bad
expect(foo).to receive(:bar).exactly(1).times
expect(foo).to receive(:bar).exactly(2).times
expect(foo).to receive(:bar).at_least(1).times
expect(foo).to receive(:bar).at_least(2).times
expect(foo).to receive(:bar).at_most(1).times
expect(foo).to receive(:bar).at_most(2).times

# good
expect(foo).to receive(:bar).once
expect(foo).to receive(:bar).twice
expect(foo).to receive(:bar).at_least(:once)
expect(foo).to receive(:bar).at_least(:twice)
expect(foo).to receive(:bar).at_most(:once)
expect(foo).to receive(:bar).at_most(:twice).times

Constant Summary collapse

MSG =
'Use `%<alternative>s` instead of `%<original>s`.'

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

#autocorrect(node) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
# File 'lib/rubocop/cop/rspec/receive_counts.rb', line 49

def autocorrect(node)
  lambda do |corrector|
    replacement = matcher_for(
      node.method_name,
      node.first_argument.source.to_i
    )

    original = range(node.parent, node)
    corrector.replace(original, replacement)
  end
end

#on_send(node) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/rubocop/cop/rspec/receive_counts.rb', line 35

def on_send(node)
  receive_counts(node) do |offending_node|
    return unless stub?(offending_node.receiver)

    offending_range = range(node, offending_node)

    add_offense(
      offending_node,
      message: message_for(offending_node, offending_range.source),
      location: offending_range
    )
  end
end