Ruby on rails 使用rspec测试oauth2 get_令牌
我正在为oauth2身份验证的get_令牌部分创建一个控制器规范。此时,用户已授权我的应用程序,我需要生成并保存令牌和其他信息。Rspec失败时出现了一个隐晦的错误Ruby on rails 使用rspec测试oauth2 get_令牌,ruby-on-rails,ruby-on-rails-4,rspec,oauth-2.0,webmock,Ruby On Rails,Ruby On Rails 4,Rspec,Oauth 2.0,Webmock,我正在为oauth2身份验证的get_令牌部分创建一个控制器规范。此时,用户已授权我的应用程序,我需要生成并保存令牌和其他信息。Rspec失败时出现了一个隐晦的错误 Failure/Error: get :auth, { code: "auth_code", scope: "read_write" } OAuth2::Error: {:token_type=>"bearer", :stripe_publishable_key=>"PUBLIS
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_令牌上失败
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_令牌。正是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
这个过程在实践中已经起作用了,所以至少控制器代码不应该受到责备。我做错了什么?我认为您遇到了这个错误,因为您只中断了oauth会话的一部分,即您试图发送webmock提供的过时令牌(或类似的东西) 我建议使用专门为测试StripeAPI而设计的工具:,而不是手动截取这些请求
作为一种替代方法,您可以使用(这里有),它允许在磁盘上写入所有http会话,并在它处于活动状态时播放。非常好的工具,强烈推荐。在努力解决了同样的问题后,我有了一个解决方案。是存根请求中返回的头,则为空。oauth2 gem使用内容类型来定义如何解析主体。尝试以以下方式放置标题的存根:
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'})