rspec RSpec Mocks Stubbing with allow


Example

The following example uses allow and receive to stub a Cart's call to a CreditCardService so that the example doesn't have to wait for a network call or use a credit card number that the processor knows about.

class Cart
  def check_out
    begin
      transaction_id = CreditCardService.instance.validate credit_card_number, total_price
      order = Order.new
      order.items = cart.items
      order
    rescue CreditCardService::ValidationFailedError
      # handle the error
    end
  end
end

describe Cart do
  describe '#check_out' do
    it "places an order" do
      allow(CreditCardService.instance).
        to receive(:validate).with("1234567812345678", 3700).and_return("transaction_id")
      cart = Cart.new
      cart.items << Item.new("Propeller beanie", 3700)
      order = cart.check_out
      expect(order.transaction_id).to eq("transaction_id")
    end
  end
end

with is optional; without it, any arguments are accepted. and_return is optional too; without it the stub returns nil.