使函数的主体使用对象的模拟

时间:2015-01-07 12:56:48

标签: ruby testing ruby-on-rails-4 rspec stripe-payments

我在控制器中有以下方法:

def webhook
    data_json = JSON.parse(request.body.read) # it comes from the test, it's OK
    event = Stripe::Event.retrieve(data_json[:id]) # it's not OK, it's a real request to Stripe
    stripe_cust_id = event.data.object.customer
    user = User.where(stripe_customer_id: stripe_cust_id)
    #.....

在spec文件中,我为event创建了一个模拟,然后在测试中向webhook发送了一个帖子请求。我不允许更改webhook的正文或签名,因为我正在测试它。那么如何让它使用我创建的模拟?

describe '#webhook' do
    it 'something' do
      user = FactoryGirl.create(:user)
      event = StripeMock.mock_webhook_event('invoice.payment_succeeded')
      post(:webhook, event.to_json)

      #error because webhook makes a real request to Stripe

2 个答案:

答案 0 :(得分:1)

mock(Stripe::Event).retrieve(any) do
  event
end

这应该从event上的retrieve的任何电话回复Stripe::Event。适用于rr

答案 1 :(得分:1)

如果您只关注外部请求,可以尝试使用VcrWebMock来模拟回复。