Rspec의 Request Spec에서 Stripe-Signature 헤더를 포함한 테스트

Stripe를 이용하고 있고 webhook를 사용한 Stripe상에서 발생한 이벤트에 대해서 처리를 실시한다고 하는 것은 자주 있다고 생각합니다.

Stripe에서는 이벤트가 타사가 아닌 Stripe에서 보낸 요청인지 확인하기 위해 Signature를 확인할 수 있습니다.
Check the webhook signatures

기본적으로 webhook에서 이벤트를 받는 엔드포인트에서 Signature 확인 처리를 수행할 것이라고 생각하지만, 테스트에서는 자체적으로 Signature를 작성해야 합니다.

이 섹션에서는 공식 Stripe API의 Ruby Gems stripe-ruby 및 Rspec을 사용하여 테스트하는 전제 예를 설명합니다.
  • stripe/stripe-ruby: Ruby library for the Stripe API.

  • Stripe-Signature 만들기



    stripe-ruby는 Signature 계산과 Stripe-Signature 헤더의 문자열을 만드는 메소드를 제공합니다.
    이것들을 사용해 Stripe-Signature 헤더를 포함한 POST 요청을 하는 메소드를 준비합니다.
  • Method: Stripe::Webhook::Signature.compute_signature — Documentation for stripe/stripe-ruby (master)
  • Method: Stripe::Webhook::Signature.generate_header — Documentation for stripe/stripe-ruby (master)

  • spec/support/stripe_webhook_helpers.rb
    # frozen_string_literal: true
    
    module StripeEventHelpers
      def post_with_stripe_signature(path, **options)
        post(
          path,
          headers: {
            'Stripe-Signature': generate_stripe_event_signature(options[:params])
          },
          **options
        )
      end
    
      private
    
      def generate_stripe_event_signature(payload)
        time = Time.now
        secret = ENV['STRIPE_WEBHOOK_SECRET']
        signature = Stripe::Webhook::Signature.compute_signature(time, payload, secret)
        Stripe::Webhook::Signature.generate_header(
          time,
          signature
        )
      end
    end
    

    Stripe 의 이벤트를 받는 엔드포인트의 테스트내에서의 post 는 기본적으로 Stripe-Signature 헤더를 포함하게 되므로 post 를 오버라이드(override) 하는 것도 있다고 생각합니다.

    spec/support/stripe_webhook_helpers.rb
    -  def post_with_stripe_signature(path, **options)
    +  def post(path, **options)
    -    post(
    +    super(
          path,
          headers: {
            'Stripe-Signature': generate_stripe_event_signature(options[:params])
          },
          **options
        )
      end
    

    도우미를 가져와 헤더를 포함한 요청



    테스트용 Stripe::Event 객체를 만들려면 stripe-ruby-mock 을 사용합니다.
    Ref : stripe-ruby-mock/stripe-ruby-mock: A mocking library for testing stripe ruby

    spec/requests/stripe_events_spec.rb
    describe StripeEventsController do
      include StripeEventHelpers
    
      before { StripeMock.start }
      after { StripeMock.stop }
    
      let(:event) { StripeMock.mock_webhook_event('customer.created') }
    
      it 'returns ok' do 
        post_with_stripe_signature stripe_events_path, params: event.to_json
        expect(response).to have_http_status(200)
      end
    end
    



    Refs


  • Including Stripe Signature header when testing with Rspec? · Issue #467 · stripe-ruby-mock/stripe-ruby-mock
  • 좋은 웹페이지 즐겨찾기