2016-09-12 100 views
0

我是RSpec的新手,並在如何使用模擬進行測試中掙扎。 當網絡掛接進來這基本上是調用。複雜情況下的Rspec

class InvoiceCreated 
    def call(event) 
    invoice = event.data.object 

    # NOTE: Skip if the invoice is closed. 
    if invoice.closed == false 
     stripe_customer = invoice.customer 
     payment_account = PaymentCardAccount.find_by(stripe_customer_id: stripe_customer) 
     card_invoice = Invoice.find_card_invoice_in_this_month_within(payment_account: payment_account) 

     card_invoice.process_invoice_items(stripe_customer: stripe_customer, 
             event_invoice_id: invoice.id) 
     card_invoice.process!(:pending, id: invoice.id) 
    end 
    end 
end 

我喜歡使用模擬和防止API調用用於測試的下面兩行代碼。

card_invoice.process_invoice_items(stripe_customer: stripe_customer, 
            event_invoice_id: invoice.id) 

    card_invoice.process!(:pending, id: invoice.id) 

我該如何使用mock?

+0

您正在使用哪種版本的rspec? – hakcho

+0

我使用'rspec-rails','〜> 3.4.2'。 – Tosh

+0

當你說「模擬」時,你究竟想在這裏實現什麼?你只是想要一個實際上不會做任何事情的虛擬對象,並且不會因爲像'NoMethodError:Undefined method process_invoice_items'這樣的錯誤而失敗。或者,您是否確實想要存儲處理髮票的Web API調用,但是要執行此功能的「全面測試」?試圖達到什麼目的? (也許你可以在上面的帖子中包含當前的測試?) –

回答

1

您可以使用expect_any_instance_of檢查是否使用正確的參數調用Invoice#process_invoice_itemsInvoice#process。如果你不關心他們是如何被調用的,你可以將它們存根並使用allow_any_instance_of

expect_any_instance_of(Invoice).to receive(:process_invoice_items) 
expect_any_instance_of(Invoice).to receive(:process!) 

See here更詳細的例子,通過rspec-mock基本款了,看你可以用它實際上做什麼。

相關問題