Rspec의 Request Spec에서 Stripe-Signature 헤더를 포함한 테스트
Stripe에서는 이벤트가 타사가 아닌 Stripe에서 보낸 요청인지 확인하기 위해 Signature를 확인할 수 있습니다.
Check the webhook signatures
기본적으로 webhook에서 이벤트를 받는 엔드포인트에서 Signature 확인 처리를 수행할 것이라고 생각하지만, 테스트에서는 자체적으로 Signature를 작성해야 합니다.
이 섹션에서는 공식 Stripe API의 Ruby Gems stripe-ruby 및 Rspec을 사용하여 테스트하는 전제 예를 설명합니다.
Stripe-Signature 만들기
stripe-ruby는 Signature 계산과 Stripe-Signature 헤더의 문자열을 만드는 메소드를 제공합니다.
이것들을 사용해 Stripe-Signature 헤더를 포함한 POST 요청을 하는 메소드를 준비합니다.
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
Reference
이 문제에 관하여(Rspec의 Request Spec에서 Stripe-Signature 헤더를 포함한 테스트), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/phigasui/items/d9ea3c8a8fd71e8ddda2텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)