我是PayPal API的新手。
我的Rails服务器会检查每笔付款是否被批准。我正在努力为此编写规范,因为我不知道该如何“伪造”批准。
我想出了三种可能性:
paymentId
。这3个人对我来说都不是很好。
因此问题仍然存在:如何为我的规格创建批准的付款?
答案 0 :(得分:2)
您应该模拟来自api的响应。您不需要实际执行请求,也没有理由不对处理api请求结果的代码进行测试。假设您要模拟以下代码:
#controller.rb
def initialize(dependencies = {})
@payment_service = dependencies.fetch(:paypal_api) do
Payment
end
end
...
def payment_method
payment = @payment_service.find("PAY-57363176S1057143SKE2HO3A")
if payment.execute(payer_id: "DUFRQ8GWYMJXC")
# Do some stuff
return 'success!'
end
'failure!'
end
您可以在Rspec中使用类似以下内容来模拟您的响应:
# controller_spec.rb
let(:paypal_api) { double('Payment') }
let(:mock_payment) { double('PayPal::SDK::REST::DataTypes::Payment') }
let(:mock_controller) { described_class.new(paypal_api: paypal_api) }
...
it 'returns the correct result when the payment is successfull' do
mock_response = {
"paymentExecuteResponse":{
"id":,
"intent":"sale",
"state":"approved",
"cart":,
"payer":{
"payment_method":"paypal",
"payer_info":{
"email":,
"first_name":,
"last_name":,
"payer_id":,
"phone":,
"country_code":
}
}
... some other stuff...
}
}
...
# This mocks the find method from the sdk
allow(paypal_api).to receive(:find).and_return(mock_payment)
# This mocks the execution of the payment
allow(mock_payment).to receive(:execute).and_return(mock_response)
result = mock_controller.payment_method
expect(result).to 'success!'
end
我还建议您看一下有关双打的rspec docs。