RSpec allow/expect vs just expect/and_return
See the classic article Mocks Aren't Stubs. allow
makes a stub while expect
makes a mock. That is allow
allows an object to return X instead of whatever it would return unstubbed, and expect
is an allow
plus an expectation of some state or event. When you write
allow(Foo).to receive(:bar).with(baz).and_return(foobar_result)
... you're telling the spec environment to modify Foo
to return foobar_result
when it receives :bar
with baz
. But when you write
expect(Foo).to receive(:bar).with(baz).and_return(foobar_result)
... you're doing the same, plus telling the spec to fail unless Foo
receives :bar
with baz
.
To see the difference, try both in examples where Foo
does not receive :bar
with baz
.