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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
|
class MockObject
def initialize(name, options = {})
@name = name
@null = options[:null_object]
end
def method_missing(sym, *args, &block)
@null ? self : super
end
private :method_missing
end
class NumericMockObject < Numeric
def initialize(name, options = {})
@name = name
@null = options[:null_object]
end
def method_missing(sym, *args, &block)
@null ? self : super
end
def singleton_method_added(val)
end
end
class MockIntObject
def initialize(val)
@value = val
@calls = 0
key = [self, :to_int]
Mock.objects[key] = self
Mock.mocks[key] << self
end
attr_reader :calls
def to_int
@calls += 1
@value.to_int
end
def count
[:at_least, 1]
end
end
class MockProxy
attr_reader :raising, :yielding
def initialize(type = nil)
@multiple_returns = nil
@returning = nil
@raising = nil
@yielding = []
@arguments = :any_args
@type = type || :mock
end
def mock?
@type == :mock
end
def stub?
@type == :stub
end
def count
@count ||= mock? ? [:exactly, 1] : [:any_number_of_times, 0]
end
def arguments
@arguments
end
def returning
if @multiple_returns
if @returning.size == 1
@multiple_returns = false
return @returning = @returning.shift
end
return @returning.shift
end
@returning
end
def times
self
end
def calls
@calls ||= 0
end
def called
@calls = calls + 1
end
def exactly(n)
@count = [:exactly, n_times(n)]
self
end
def at_least(n)
@count = [:at_least, n_times(n)]
self
end
def at_most(n)
@count = [:at_most, n_times(n)]
self
end
def once
exactly 1
end
def twice
exactly 2
end
def any_number_of_times
@count = [:any_number_of_times, 0]
self
end
def with(*args)
raise ArgumentError, "you must specify the expected arguments" if args.empty?
if args.length == 1
@arguments = args.first
else
@arguments = args
end
self
end
def and_return(*args)
case args.size
when 0
@returning = nil
when 1
@returning = args[0]
else
@multiple_returns = true
@returning = args
count[1] = args.size if count[1] < args.size
end
self
end
def and_raise(exception)
if exception.kind_of? String
@raising = RuntimeError.new exception
else
@raising = exception
end
end
def raising?
@raising != nil
end
def and_yield(*args)
@yielding << args
self
end
def yielding?
!@yielding.empty?
end
private
def n_times(n)
case n
when :once
1
when :twice
2
else
Integer n
end
end
end
|