與允許結合
以下示例使用 allow
和 receive
將 Cart
的呼叫存根到 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
。