与允许结合

以下示例使用 allowreceiveCart 的调用存根到 CreditCardService,以便示例不必等待网络呼叫或使用处理器知道的信用卡号。

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 是可选的; 没有它,任何论据都被接受。and_return 也是可选的; 没有它,存根返回 nil