Oauth2 get_token test with rspec
I am creating a controller spec for the get_token part of oauth2 authentication. At this point the user has authorized my application and I need to generate and save a token and other information. Rspec is failing with some cryptic error.
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"}
Here is the controller code. Rspec says it doesn't work for 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
And here's the test. The webmock must intercept get_token. This is an autogenerated webmock suggested by rspec that I have filled in the body with the appropriate request and response body.
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
This process already works in practice, so at least the controller code is not at fault. What am I doing wrong?
source to share
I think you are getting this error because you only missed part of the oauth session i.e. you are trying to send an obsolete token (or something like that) that was provided by webmock.
Instead of manually copying these requests, I would suggest using a dedicated tool: stripe-ruby-mock gem , which was designed specifically for testing the Stripe API.
Alternatively, you can use the VCR
gem (here's the docs ), which allows you to record your entire http session to disk and play it back as it did live. Great tool recommended.
source to share