-
Notifications
You must be signed in to change notification settings - Fork 5
Anonymous Doubles
Mike Miller edited this page Mar 7, 2020
·
3 revisions
Anonymous doubles provide a quick way to create a double.
They don't need a definition block outside of a test.
However, all methods that are expected to be called must be specified in the double()
call.
Additionally, the name of the double is a string literal.
anon = double("Anon", foo: 42)
expect(anon.foo).to eq(42)
Stubs can be used, as long as the types match.
anon = double("Anon", foo: 42)
allow(anon).to receive(:foo).and_return(123)
expect(anon.foo).to eq(123)
Note: Anonymous doubles should not be used when the return type is statically checked at compile time.
The return type of all methods for an anonymous double is the union of all the types used in the double()
call plus nil.
In the following code:
anon = double("Anon", foo: 42, bar: "foobar")
puts typeof(anon.foo)
Produces (Int32 | String | Nil)
.