class RuboCop::Cop::RSpec::ReceiveCounts
Check for ‘once` and `twice` receive counts matchers usage.
@example
# 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
Constants
- MSG
- RESTRICT_ON_SEND
Public Instance Methods
Source
# 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
Private Instance Methods
Source
# File lib/rubocop/cop/rspec/receive_counts.rb, line 55 def autocorrect(corrector, node, range) replacement = matcher_for( node.method_name, node.first_argument.source.to_i ) corrector.replace(range, replacement) end
Source
# File lib/rubocop/cop/rspec/receive_counts.rb, line 72 def matcher_for(method, count) matcher = count == 1 ? 'once' : 'twice' if method == :exactly ".#{matcher}" else ".#{method}(:#{matcher})" end end
Source
# File lib/rubocop/cop/rspec/receive_counts.rb, line 64 def message_for(node, source) alternative = matcher_for( node.method_name, node.first_argument.source.to_i ) format(MSG, alternative: alternative, original: source) end
Source
# File lib/rubocop/cop/rspec/receive_counts.rb, line 81 def range(node, offending_node) offending_node.loc.dot.with( end_pos: node.source_range.end_pos ) end