我正在为oauth2身份验证的get_token部分创建一个控制器规范。此时,用户已授权我的应用程序,我需要生成并保存令牌和其他信息。
Failure/Error: get :auth, { code: "auth_code", scope: "read_write" }
OAuth2::Error:
{:token_type=>"bearer",
:stripe_publishable_key=>"PUBLISHABLE_KEY",
:scope=>"read_write",
:livemode=>"false",
:stripe_user_id=>"USER_ID",
:refresh_token=>"REFRESH_TOKEN",
:access_token=>"ACCESS_TOKEN"}
这是控制器代码。Rspec说它在get_token上失败。
require 'oauth2'
def auth
code = params[:code]
client = oauth_client
token_response = client.auth_code.get_token(code, params: { scope: 'read_write' })
token = token_response.token
测试是这样的。webmock应该拦截get_token。这是rspec建议的自动生成的webmock,我在主体中填充了适当的请求和响应主体。
before do
stub_request(:post, "https://connect.stripe.com/oauth/token").
with(:body => {"client_id"=>"CLIENT_ID",
"client_secret"=>"SOME_SECRET",
"code"=>"auth_code",
"grant_type"=>"authorization_code",
"params"=>{"scope"=>"read_write"}},
:headers => {'Accept'=>'*/*',
'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
'Content-Type'=>'application/x-www-form-urlencoded',
'User-Agent'=>'Faraday v0.9.0'}).
to_return(:status => 200,
:body => {token_type: "bearer",
stripe_publishable_key: "PUBLISHABLE_KEY",
scope: "read_write",
livemode: "false",
stripe_user_id: "USER_ID",
refresh_token: "REFRESH_TOKEN",
access_token: "ACCESS_TOKEN"},
:headers => {})
end
describe "#auth" do
it "creates a payment gateway" do
get :auth, { code: "auth_code", scope: "read_write"
end
end
这个过程已经在实践中工作了,所以至少控制器代码不应该受到指责。我做错了什么?
经过努力,遇到同样的问题,我有了解决方案。如果在存根请求中返回报头,则将其设置为空白。oauth2 gem使用Content-Type来定义如何解析正文。试着用这样的方式来保存存根:
stub_request(:post, "https://connect.stripe.com/oauth/token").
with(:body => {"client_id"=>"CLIENT_ID",
"client_secret"=>"SOME_SECRET",
"code"=>"auth_code",
"grant_type"=>"authorization_code",
"params"=>{"scope"=>"read_write"}},
:headers => {'Accept'=>'*/*',
'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
'Content-Type'=>'application/x-www-form-urlencoded',
'User-Agent'=>'Faraday v0.9.0'}).
to_return(:status => 200,
:body => {token_type: "bearer",
stripe_publishable_key: "PUBLISHABLE_KEY",
scope: "read_write",
livemode: "false",
stripe_user_id: "USER_ID",
refresh_token: "REFRESH_TOKEN",
access_token: "ACCESS_TOKEN"},
:headers => { 'Content-Type'=> 'application/json;charset=UTF-8'})
我认为你得到这个错误,因为你只stub了oauth会话的一部分,即你试图发送一个由webmock提供的陈旧令牌(或类似的东西)。
我建议使用特殊的工具:Stripe -ruby-mock gem,它是专门为测试Stripe API而设计的。
作为替代方案,您可以使用VCR
gem(这里是文档),它允许将所有http会话写入磁盘并将其作为现场播放。很好的工具,强烈推荐。