File: 03_api_overview.md

package info (click to toggle)
ruby-rr 1.1.2-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 1,464 kB
  • ctags: 1,554
  • sloc: ruby: 12,632; makefile: 4
file content (616 lines) | stat: -rw-r--r-- 14,154 bytes parent folder | download | duplicates (5)
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
# API overview

To create a double on an object, you can use the following methods:

* #mock / #mock!
* #stub / #stub!
* #dont_allow / #dont_allow!
* #proxy / #proxy!
* #instance_of / #instance_of!

These methods are composable. #mock, #stub, and #dont_allow can be used by
themselves and are mutually exclusive. #proxy and #instance_of must be chained
with #mock or #stub. You can also chain #proxy and #instance_of together.

The ! (bang) version of these methods causes the subject object of the Double to
be instantiated.

## #mock

\#mock replaces the method on the object with an expectation and implementation.
The expectations are a mock will be called with certain arguments a certain
number of times (the default is once). You can also set the return value of the
method invocation.

*Learn more: <http://xunitpatterns.com/Mock%20Object.html>*

The following example sets an expectation that the view will receive a method
call to #render with the arguments `{:partial => "user_info"}` once. When the
method is called, `"Information"` is returned.

~~~ ruby
view = controller.template
mock(view).render(:partial => "user_info") {"Information"}
~~~

You can also allow any number of arguments to be passed into the mock like
this:

~~~ ruby
mock(view).render.with_any_args.twice do |*args|
  if args.first == {:partial => "user_info"}
    "User Info"
  else
    "Stuff in the view #{args.inspect}"
  end
end
~~~

## #stub

\#stub replaces the method on the object with only an implementation. You can
still use arguments to differentiate which stub gets invoked.

*Learn more: <http://xunitpatterns.com/Test%20Stub.html>*

The following example makes the User.find method return `jane` when passed "42"
and returns `bob` when passed "99". If another id is passed to User.find, an
exception is raised.

~~~ ruby
jane = User.new
bob = User.new
stub(User).find('42') {jane}
stub(User).find('99') {bob}
stub(User).find do |id|
  raise "Unexpected id #{id.inspect} passed to me"
end
~~~

## #dont_allow (aliased to #do_not_allow, #dont_call, and #do_not_call)

\#dont_allow is the opposite of #mock -- it sets an expectation on the Double
that it will never be called. If the Double actually does end up being called, a
TimesCalledError is raised.

~~~ ruby
dont_allow(User).find('42')
User.find('42') # raises a TimesCalledError
~~~

## `mock.proxy`

`mock.proxy` replaces the method on the object with an expectation,
implementation, and also invokes the actual method. `mock.proxy` also intercepts
the return value and passes it into the return value block.

The following example makes sets an expectation that `view.render({:partial =>
"right_navigation"})` gets called once and returns the actual content of the
rendered partial template. A call to `view.render({:partial => "user_info"})`
will render the "user_info" partial template and send the content into the block
and is represented by the `html` variable. An assertion is done on the value of
`html` and `"Different html"` is returned.

~~~ ruby
view = controller.template
mock.proxy(view).render(:partial => "right_navigation")
mock.proxy(view).render(:partial => "user_info") do |html|
  html.should include("John Doe")
  "Different html"
end
~~~

You can also use `mock.proxy` to set expectations on the returned value. In the
following example, a call to User.find('5') does the normal ActiveRecord
implementation and passes the actual value, represented by the variable `bob`,
into the block. `bob` is then set with a `mock.proxy` for projects to return only
the first 3 projects. `bob` is also mocked so that #valid? returns false.

~~~ ruby
mock.proxy(User).find('5') do |bob|
  mock.proxy(bob).projects do |projects|
    projects[0..3]
  end
  mock(bob).valid? { false }
  bob
end
~~~

## `stub.proxy`

Intercept the return value of a method call. The following example verifies
`render(:partial)` will be called and renders the partial.

~~~ ruby
view = controller.template
stub.proxy(view).render(:partial => "user_info") do |html|
  html.should include("Joe Smith")
  html
end
~~~

## #any_instance_of

Allows stubs to be added to all instances of a class. It works by binding to
methods from the class itself, rather than the eigenclass. This allows all
instances (excluding instances with the method redefined in the eigenclass) to
get the change.

Due to Ruby runtime limitations, mocks will not work as expected. It's not
obviously feasible (without an ObjectSpace lookup) to support all of RR's
methods (such as mocking). ObjectSpace is not readily supported in JRuby, since
it causes general slowness in the interpreter. I'm of the opinion that test
speed is more important than having mocks on all instances of a class. If there
is another solution, I'd be willing to add it.

~~~ ruby
any_instance_of(User) do |u|
  stub(u).valid? { false }
end
 or
any_instance_of(User, :valid? => false)
 or
any_instance_of(User, :valid? => lambda { false })
~~~

## Spies

Adding a DoubleInjection to an object + method (done by #stub, #mock, or
\#dont_allow) causes RR to record any method invocations to the object + method.
Assertions can then be made on the recorded method calls.

### Test::Unit

~~~ ruby
subject = Object.new
stub(subject).foo
subject.foo(1)
assert_received(subject) {|subject| subject.foo(1) }
assert_received(subject) {|subject| subject.bar }  # This fails
~~~

### RSpec

~~~ ruby
subject = Object.new
stub(subject).foo
subject.foo(1)
subject.should have_received.foo(1)
subject.should have_received.bar  # This fails
~~~

## Block syntax

The block syntax has two modes:

* A normal block mode with a DoubleDefinitionCreatorProxy argument:

  ~~~ ruby
  script = MyScript.new
  mock(script) do |expect|
    expect.system("cd #{RAILS_ENV}") {true}
    expect.system("rake foo:bar") {true}
    expect.system("rake baz") {true}
  end
  ~~~

* An instance_eval mode where the DoubleDefinitionCreatorProxy is
  instance_eval'ed:

  ~~~ ruby
  script = MyScript.new
  mock(script) do
    system("cd #{RAILS_ENV}") {true}
    system("rake foo:bar") {true}
    system("rake baz") {true}
  end
  ~~~

## Double graphs

RR has a method-chaining API support for double graphs. For example, let's say
you want an object to receive a method call to #foo, and have the return value
receive a method call to #bar.

In RR, you would do:

~~~ ruby
stub(object).foo.stub!.bar { :baz }
object.foo.bar  #=> :baz
 or:
stub(object).foo { stub!.bar {:baz} }
object.foo.bar  #=> :baz
 or:
bar = stub!.bar { :baz }
stub(object).foo { bar }
object.foo.bar  #=> :baz
~~~

## Modifying doubles

Whenever you create a double by calling a method on an object you've wrapped,
you get back a special object: a DoubleDefinition. In other words:

~~~ ruby
stub(object).foo     #=> RR::DoubleDefinitions::DoubleDefinition
~~~

There are several ways you can modify the behavior of these doubles via the
DoubleDefinition API, and they are listed in this section.

Quick note: all of these methods accept blocks as a shortcut for setting the
return value at the same time. In other words, if you have something like this:

~~~ ruby
mock(object).foo { 'bar' }
~~~

you can modify the mock and keep the return value like so:

~~~ ruby
mock(object).foo.times(2) { 'bar' }
~~~

You can even flip around the block:

~~~ ruby
mock(object).foo { 'bar' }.times(2)
~~~

And as we explain below, this is just a shortcut for:

~~~ ruby
mock(object).foo.returns { 'bar' }.times(2)
~~~

### Stubbing method implementation / return value

There are two ways here. We have already covered this usage:

~~~ ruby
stub(object).foo { 'bar' }
~~~

However, you can also use #returns if it's more clear to you:

~~~ ruby
stub(object).foo.returns { 'bar' }
~~~

Regardless, keep in mind that you're actually supplying the implementation of
the method in question here, so you can put whatever you want in this block:

~~~ ruby
stub(object).foo { |age, count|
  raise 'hell' if age < 16
  ret = yield count
  blue? ? ret : 'whatever'
}
~~~

This works for mocks as well as stubs.

### Stubbing method implementation based on argument expectation

A double's implementation is always tied to its argument expectation. This means
that it is possible to return one value if the method is called one way and
return a second value if the method is called a second way. For example:

~~~ ruby
stub(object).foo { 'bar' }
stub(object).foo(1, 2) { 'baz' }
object.foo        #=> 'bar'
object.foo(1, 2)  #=> 'baz'
~~~

This works for mocks as well as stubs.

### Stubbing method to yield given block

If you need to stub a method such that a block given to it is guaranteed to be
called when the method is called, then use #yields.

~~~ ruby
 This outputs: [1, 2, 3]
stub(object).foo.yields(1, 2, 3)
object.foo {|*args| pp args }
~~~

This works for mocks as well as stubs.

### Expecting method to be called with exact argument list

There are two ways to do this. Here is the way we have shown before:

~~~ ruby
mock(object).foo(1, 2)
object.foo(1, 2)   # ok
object.foo(3)      # fails
~~~

But if this is not clear enough to you, you can use #with:

~~~ ruby
mock(object).foo.with(1, 2)
object.foo(1, 2)   # ok
object.foo(3)      # fails
~~~

As seen above, if you create an the expectation for a set of arguments and the
method is called with another set of arguments, even if *those* arguments are of
a completely different size, you will need to create another expectation for
them somehow. A simple way to do this is to #stub the method beforehand:

~~~ ruby
stub(object).foo
mock(object).foo(1, 2)
object.foo(1, 2)   # ok
object.foo(3)      # ok too
~~~

### Expecting method to be called with any arguments

Use #with_any_args:

~~~ ruby
mock(object).foo.with_any_args
object.foo        # ok
object.foo(1)     # also ok
object.foo(1, 2)  # also ok
                  # ... you get the idea
~~~

### Expecting method to be called with no arguments

Use #with_no_args:

~~~ ruby
mock(object).foo.with_no_args
object.foo        # ok
object.foo(1)     # fails
~~~

### Expecting method to never be called

Use #never:

~~~ ruby
mock(object).foo.never
object.foo        # fails
~~~

You can also narrow the negative expectation to a specific set of arguments.
Of course, you will still need to set explicit expectations for any other ways
that your method could be called. For instance:

~~~ ruby
mock(object).foo.with(1, 2).never
object.foo(3, 4)  # fails
~~~

RR will complain here that this is an unexpected invocation, so we need to add
an expectation for this beforehand. We can do this easily with #stub:

~~~ ruby
stub(object).foo
~~~

So, a full example would look like:

~~~ ruby
stub(object).foo
mock(object).foo.with(1, 2).never
object.foo(3, 4)   # ok
object.foo(1, 2)   # fails
~~~

Alternatively, you can also use #dont_allow, although the same rules apply as
above:

~~~ ruby
stub(object).foo
dont_allow(object).foo.with(1, 2)
object.foo(3, 4)   # ok
object.foo(1, 2)   # fails
~~~

### Expecting method to be called only once

Use #once:

~~~ ruby
mock(object).foo.once
object.foo
object.foo    # fails
~~~

### Expecting method to called exact number of times

Use #times:

~~~ ruby
mock(object).foo.times(3)
object.foo
object.foo
object.foo
object.foo    # fails
~~~

### Expecting method to be called minimum number of times

Use #at_least.

For instance, this would pass:

~~~ ruby
mock(object).foo.at_least(3)
object.foo
object.foo
object.foo
object.foo
~~~

But this would fail:

~~~ ruby
mock(object).foo.at_least(3)
object.foo
object.foo
~~~

### Expecting method to be called maximum number of times

Use #at_most.

For instance, this would pass:

~~~ ruby
mock(object).foo.at_most(3)
object.foo
object.foo
~~~

But this would fail:

~~~ ruby
mock(object).foo.at_most(3)
object.foo
object.foo
object.foo
object.foo
~~~

### Expecting method to be called any number of times

Use #any_times. This effectively disables the times-called expectation.

~~~ ruby
mock(object).foo.any_times
object.foo
object.foo
object.foo
...
~~~

You can also use #times + the argument invocation #any_times matcher:

~~~ ruby
mock(object).foo.times(any_times)
object.foo
object.foo
object.foo
...
~~~



## Argument wildcard matchers

RR also has several methods which you can use with argument expectations which
act as placeholders for arguments. When RR goes to verify the argument
expectation it will compare the placeholders with the actual arguments the
method was called with, and if they match then the test passes (hence
"matchers").

### #anything

Matches any value.

~~~ ruby
mock(object).foobar(1, anything)
object.foobar(1, :my_symbol)
~~~

### #is_a

Matches an object which `.is_a?(*Class*)`.

~~~ ruby
mock(object).foobar(is_a(Time))
object.foobar(Time.now)
~~~

### #numeric

Matches a value which `.is_a?(Numeric)`.

~~~ ruby
mock(object).foobar(numeric)
object.foobar(99)
~~~~

### #boolean

Matches true or false.

~~~ ruby
mock(object).foobar(boolean)
object.foobar(false)
~~~

### #duck_type

Matches an object which responds to certain methods.

~~~ ruby
mock(object).foobar(duck_type(:walk, :talk))
arg = Object.new
def arg.walk; 'waddle'; end
def arg.talk; 'quack'; end
object.foobar(arg)
~~~

### Ranges

Matches a number within a certain range.

~~~ ruby
mock(object).foobar(1..10)
object.foobar(5)
~~~

### Regexps

Matches a string which matches a certain regex.

~~~ ruby
mock(object).foobar(/on/)
object.foobar("ruby on rails")
~~~

### #hash_including

Matches a hash which contains a subset of keys and values.

~~~ ruby
mock(object).foobar(hash_including(:red => "#FF0000", :blue => "#0000FF"))
object.foobar({:red => "#FF0000", :blue => "#0000FF", :green => "#00FF00"})
~~~

### #satisfy

Matches an argument which satisfies a custom requirement.

~~~ ruby
mock(object).foobar(satisfy {|arg| arg.length == 2 })
object.foobar("xy")
~~~

### Writing your own argument matchers

Writing a custom argument wildcard matcher is not difficult.  See
RR::WildcardMatchers for details.

## Invocation amount wildcard matchers

### #any_times

Only used with #times and matches any number.

~~~ ruby
mock(object).foo.times(any_times) { return_value }
object.foo
object.foo
object.foo
...
~~~