/
order_group.rb
82 lines (67 loc) · 1.82 KB
/
order_group.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
module RSpec
module Mocks
# @private
class OrderGroup
def initialize
@expectations = []
@invocation_order = []
@index = 0
end
# @private
def register(expectation)
@expectations << expectation
end
def invoked(message)
@invocation_order << message
end
# @private
def ready_for?(expectation)
remaining_expectations.find(&:ordered?) == expectation
end
# @private
def consume
remaining_expectations.each_with_index do |expectation, index|
if expectation.ordered?
@index += index + 1
return expectation
end
end
nil
end
# @private
def handle_order_constraint(expectation)
return unless expectation.ordered? && remaining_expectations.include?(expectation)
return consume if ready_for?(expectation)
expectation.raise_out_of_order_error
end
def verify_invocation_order(expectation)
expectation.raise_out_of_order_error unless expectations_invoked_in_order?
true
end
def clear
@index = 0
@invocation_order.clear
@expectations.clear
end
def empty?
@expectations.empty?
end
private
def remaining_expectations
@expectations[@index..-1] || []
end
def expectations_invoked_in_order?
invoked_expectations == expected_invocations
end
def invoked_expectations
@expectations.select { |e| e.ordered? && @invocation_order.include?(e) }
end
def expected_invocations
@invocation_order.map { |invocation| expectation_for(invocation) }.compact
end
def expectation_for(message)
@expectations.find { |e| message == e }
end
end
end
end