-
Notifications
You must be signed in to change notification settings - Fork 5
Anonymous Doubles
Mike Miller edited this page Jul 15, 2022
·
3 revisions
Anonymous doubles (sometimes called lazy 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 as key-value pairs (keyword arguments).
To create one, call double
(or new_double
) without a name.
it "does something" do
dbl = double(foo: 42)
expect(dbl.foo).to eq(42)
end
Stubs can be redefined with allow
as long as the return types match.
it "does something" do
dbl = double(foo: 42)
allow(dbl).to receive(:foo).and_return(123)
expect(dbl.foo).to eq(123)
end
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(foo: 42, bar: "foobar")
puts typeof(anon.foo)
Produces (Int32 | String | Nil)
.