The following example uses expect
and receive
to mock an Order
's call to a CreditCardService
, so that the test passes only if the call is made without having to actually make it.
class Order
def cancel
CreditCardService.instance.refund transaction_id
end
end
describe Order do
describe '#cancel' do
it "refunds the money" do
order = Order.new
order.transaction_id = "transaction_id"
expect(CreditCardService.instance).to receive(:refund).with("transaction_id")
order.cancel
end
end
end
In this example the mock is on the return value of CreditCardService.instance
, which is presumably a singleton.
with
is optional; without it, any call to refund
would satisfy the expectation. A return value could be given with and_return
; in this example it is not used, so the call returns nil
.