tansengming / stripe-rails

A Rails Engine for integrating with Stripe
MIT License
753 stars 123 forks source link

Can't provide "previous_attributes" for 'customer.subscription.updated' event #185

Closed ndbroadbent closed 4 years ago

ndbroadbent commented 4 years ago

Hello!

I'm trying to write a test for some code that relies on the "previous_attributes" section in a Stripe event. Stripe::Rails::Testing.send_event('customer.subscription.updated', ...) only takes two arguments, and it sends an event that contains the following data:

    :previous_attributes => {
        :plan => {
                           :id => "OLD_PLAN_ID",
                     :interval => "month",
                         :name => "Old plan",
                       :amount => 100,
                     :currency => "usd",
                       :object => "plan",
                     :livemode => false,
               :interval_count => 1,
            :trial_period_days => nil
        }
    }

(From this fixture: https://github.com/stripe-ruby-mock/stripe-ruby-mock/blob/master/lib/stripe_mock/webhook_fixtures/customer.subscription.updated.json#L64-L76)

It doesn't look there's any way to override this data. (I need to set the previous plan id.) Would it be possible to add support for this? Thanks!

ndbroadbent commented 4 years ago

Ahhh, it looks like this is a limitation in stripe-ruby-mock.

For now, I can just mock the StripeMock#mock_webhook_payload method in my test and wrap it with some code that adjusts the previous_attributes. Here's how I did that:

expect(StripeMock).to receive(:mock_webhook_payload).and_wrap_original do |m, *args|
  event_data = m.call(*args)
  event_data[:data][:previous_attributes] = {
    plan: {
      id: :plan_id,
      name: 'Plan name",
      amount: 1200,
    },
  }
  event_data
end

(Caveat: This only works if your test sends a single webhook.)