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

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
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`.'
RESTRICT_ON_SEND =
%i[times].freeze

Instance Method Summary collapse

Methods inherited from Base

inherited, #on_new_investigation

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



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/rubocop/cop/rspec/receive_counts.rb', line 40

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

    offending_range = range(node, offending_node)

    msg = message_for(offending_node, offending_range.source)
    add_offense(offending_range, message: msg) do |corrector|
      autocorrect(corrector, offending_node, offending_range)
    end
  end
end

#receive_counts(node) ⇒ Object



33
34
35
# File 'lib/rubocop/cop/rspec/receive_counts.rb', line 33

def_node_matcher :receive_counts, <<~PATTERN
  (send $(send _ {:exactly :at_least :at_most} (int {1 2})) :times)
PATTERN

#stub?(node) ⇒ Object



38
# File 'lib/rubocop/cop/rspec/receive_counts.rb', line 38

def_node_search :stub?, '(send nil? :receive ...)'