Rspec用于复杂的情况

时间:2016-09-12 10:57:01

标签: ruby-on-rails ruby rspec

我是RSpec的新手,并且正在努力学习如何使用mock进行测试。 这基本上是在webhook进来时调用的。

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

我喜欢使用mock并阻止API调用以测试下面两行代码。

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

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

我该如何使用mock?

1 个答案:

答案 0 :(得分: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的基本部分了解您可以用它做些什么。