forked from rubocop/rubocop-rspec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
receive_counts.rb
88 lines (76 loc) · 2.54 KB
/
receive_counts.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# frozen_string_literal: true
module RuboCop
module Cop
module RSpec
# 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
#
class ReceiveCounts < Cop
MSG = 'Use `%<alternative>s` instead of `%<original>s`.'
def_node_matcher :receive_counts, <<-PATTERN
(send $(send _ {:exactly :at_least :at_most} (int {1 2})) :times)
PATTERN
def_node_search :stub?, '(send nil? :receive ...)'
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
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
private
def message_for(node, source)
alternative = matcher_for(
node.method_name,
node.first_argument.source.to_i
)
format(MSG, alternative: alternative, original: source)
end
def matcher_for(method, count)
matcher = count == 1 ? 'once' : 'twice'
if method == :exactly
".#{matcher}"
else
".#{method}(:#{matcher})"
end
end
def range(node, offending_node)
offending_node.loc.dot.with(
end_pos: node.loc.expression.end_pos
)
end
end
end
end
end