【问题标题】:RSpec allow_any_instance_of does not work within request testRSpec allow_any_instance_of 在请求测试中不起作用
【发布时间】:2016-09-16 04:26:55
【问题描述】:

我是 RSpec 的新手,正在测试一些带有请求类型的 webhook 测试。 但是在这里,即使我使用allow_any_instance_of,它也会出错got 500 instead of 200。我用binding.pry 检查了每个变量,但似乎一切正常。 在我看来,模拟失败了,所以它返回500。 有什么想法吗?

describe "stripe_invoice_created_webhook", type: :request do

  let(:card_invoice){ create(:card_invoice, id: invoice.id) }
  let(:invoice){ create(:invoice, payment_account_id: payment_card_account.payment_account_id) }
  let(:payment_card_account){ create(:payment_card_account,
                                     stripe_customer_id: event.data.object.customer) }
  let(:event){ StripeMock.mock_webhook_event('invoice.created', {
    closed: false
  }) }

  it 'responds 200 to invoice_created webhook with valid endpoint' do
    allow_any_instance_of(CardInvoice).to receive(:process_invoice_items)
    allow_any_instance_of(CardInvoice).to receive(:process!)

    post '/stripe-events', event.as_json
    expect(response.status).to eq 200
    expect{ card_invoice.process_invoice_items }.not_to raise_error
    expect{ card_invoice.process! }.not_to raise_error
  end

原来的代码是

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

【问题讨论】:

    标签: ruby-on-rails ruby rspec


    【解决方案1】:

    是的,嘲笑失败了。您期望对象 CardVoice 接收进程!或 process_invoice_item 但您尚未指定返回值。 allow_any_instance_of 的语法是

    allow_any_instance_of(Object).to receive(:function).and_return(:return_value)
    

    【讨论】:

    • 感谢您的回答。但是 .and_return(true) 不起作用。这是为什么呢?
    猜你喜欢
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多