How we pass the headers inside swagger rspecs - ruby-on-rails

I'm getting this error when I run the rspec
Response body: {"success":false,"errors":["Invalid login credentials"]}
here is my code
path '/api/auth/validate_token' do
get 'check token' do
tags 'TokenValidations'
consumes 'application/json'
security [client: {}, uid: {}, access_token: {}]
response '200', 'success' do
let(:headers) { user.create_new_auth_token }
run_test!
end
end
end
Thanks in advance

I think I had the same problem and tried to execute below, then worked for me.
let(:user) { FactoryBot.create(:user, password: 'password') }
let(:tokens) do
post "/api/v1/authority/sign_in",
params: { email: user[:email], password: 'password' },
as: :json
response.headers.slice('client', 'access-token', 'uid')
end
path '/api/v1/messages/' do
get 'Retrieves some messages' do
description 'Get some messages from provided data'
produces 'application/json'
parameter name: 'access-token', in: :header, type: :string
parameter name: 'client', in: :header, type: :string
parameter name: 'uid', in: :header, type: :string
response '200', 'messages found' do
let(:client) { tokens['client'] }
let('access-token') { tokens['access-token'] }
let(:uid) { tokens['uid'] }
schema '$ref' => '#/components/schemas/messages'
run_test!
end
end
end

Related

Validation incoming parameters (in: :body) in rswag specs (Rails)

I have spent a lot of time trying to emplement ability of validation incoming params is rswag specs, my code:
# incoming-parameter
params = {
login: 'www',
id: 15
}
# test rswag-spec
path '/controller/hello' do
post('Say Hello!') do
tags 'users'
consumes 'application/json'
produces 'application/json'
parameter name: :my_params, in: :body, schema: {
type: :object,
required: %i[id name],
properties: {
id: { type: :string },
name: { type: :string }
}
}
response(200, 'successful') do
# schema '$ref' => '#/components/schemas/UserRegistrationResponse'
describe 'new user with valid reg_params' do
let(:my_params) { params }
run_test! do |response|
data = JSON.parse(response.body)
puts "data = #{data}"
end
end
end
end
end
You expecting that incoming params won't pass validation, because id - is an integer, and name field is absent. But that's doesn't matter and test is compliting with success.
Can you say what's wrong with my code an why don't work validation of incoming parameters those declarated in rswag docs?

Invalid access_token when using RSpec request specs to authorize a request

I'm trying to test CredentialsController, which works fine in production, using RSpec request specs.
Code
Controller
class CredentialsController < ApplicationController
before_action :doorkeeper_authorize!
def me
render json: current_user
end
end
(GET /me routes to CredentialsController#me.)
Request Specs
describe 'Credentials', type: :request do
context 'unauthorized' do
it "should 401" do
get '/me'
expect(response).to have_http_status(:unauthorized)
end
end
context 'authorized' do
let!(:application) { FactoryBot.create(:application) }
let!(:user) { FactoryBot.create(:user) }
let!(:token) { FactoryBot.create(:access_token, application: application, resource_owner_id: user.id) }
it 'succeeds' do
get '/me', params: {}, headers: {access_token: token.token}
expect(response).to be_successful
end
end
end
The unauthorized test passes, but the authorized test fails:
expected #<ActionDispatch::TestResponse:0x00007fd339411248 #mon_mutex=#<Thread::Mutex:0x00007fd339410438>, #mo..., #method=nil, #request_method=nil, #remote_ip=nil, #original_fullpath=nil, #fullpath=nil, #ip=nil>>.successful? to return true, got false
The headers indicate a problem with the token:
0> response.headers['WWW-Authenticate']
=> "Bearer realm=\"Doorkeeper\", error=\"invalid_token\", error_description=\"The access token is invalid\""
token looks okay to me, though:
0> token
=> #<Doorkeeper::AccessToken id: 7, resource_owner_id: 8, application_id: 7, token: "mnJh2wJeEEDe0G-ukNIZ6oupKQ7StxJqKPssjZTWeAk", refresh_token: nil, expires_in: 7200, revoked_at: nil, created_at: "2020-03-19 20:17:26", scopes: "public", previous_refresh_token: "">
0> token.acceptable?(Doorkeeper.config.default_scopes)
=> true
Factories
Access Token
FactoryBot.define do
factory :access_token, class: "Doorkeeper::AccessToken" do
application
expires_in { 2.hours }
scopes { "public" }
end
end
Application
FactoryBot.define do
factory :application, class: "Doorkeeper::Application" do
sequence(:name) { |n| "Project #{n}" }
sequence(:redirect_uri) { |n| "https://example#{n}.com" }
end
end
User
FactoryBot.define do
factory :user do
sequence(:email) { |n| "email#{n}#example.com" }
password { "test123" }
password_confirmation { "test123" }
end
end
Questions
Why am I getting invalid_token on this request?
Do my Doorkeeper factories look correct?
I was passing the token wrong. Instead of:
get '/me', params: {}, headers: {access_token: token.token}
I had to use:
get '/me', params: {}, headers: { 'Authorization': 'Bearer ' + token.token}
You can check your Access Token factory's scopes, It should be same as initializer's default_scopes
e.g.
config/initializers/doorkeeper.rb
default_scopes :read
Below, your Access Token factory's scopes should be
factory :access_token, class: "Doorkeeper::AccessToken" do
sequence(:resource_owner_id) { |n| n }
application
expires_in { 2.hours }
scopes { "read" }
end
Additionally, if you encountered response status: 406 while get '/me'....
It means that the requested format (by default HTML) is not supported. Instead of '.json' you can also send Accept="application/json" in the HTTP header.
get '/me', params: {}, headers: {
'Authorization': 'Bearer ' + token.token,
'Accept': 'application/json'}
I resolved my problem with this solution, maybe you can try it.

How to add component in RSWAG request parameters?

I have some common parameters which are called in almost all API calls so is it possible to create component for those parameters and call them in rswag api request.
Something like schema '$ref' => '#/definitions/parameters'
Thanks!
Add in your swagger_helper.rb
Example:
# spec/swagger_helper.rb
config.swagger_docs = {
'v1/swagger.json' => {
swagger: '2.0',
info: {
title: 'API V1'
},
definitions: {
errors_object: {
type: 'object',
properties: {
errors: { '$ref' => '#/definitions/errors_map' }
}
},
errors_map: {
type: 'object',
additionalProperties: {
type: 'array',
items: { type: 'string' }
}
}
}
}
}
# spec/integration/blogs_spec.rb
describe 'Blogs API' do
path '/blogs' do
post 'Creates a blog' do
response 422, 'invalid request' do
schema '$ref' => '#/definitions/errors_object'
...
end
# spec/integration/comments_spec.rb
describe 'Blogs API' do
path '/blogs/{blog_id}/comments' do
post 'Creates a comment' do
response 422, 'invalid request' do
schema '$ref' => '#/definitions/errors_object'
...
end
From: https://www.rubydoc.info/github/domaindrivendev/rswag#referenced-parameters-and-schema-definitions
You need to define your object in spec/swagger_helper.rb
Then in integration spec file define
path '/api/client/v0/blog' do
put 'Create a blog' do
tags :Blog
include_examples 'header_with_recognition_definitions'
parameter name: :input_param, in: :body, schema: { '$ref' => '#/definitions/input_parameter_object' }
response 200, 'blog was created successfully' do
include_examples 'header_with_recognition_lets'
...
run_test!
end
end

How create with rswag following the json api specification?

I didn't find any examples of how to use rswag to generate documentation according to json api.
spec/integration/pets_spec.rb
require 'swagger_helper'
It is possible to change the code to generate the format of json api?
describe 'Pets API' do
path '/api/v1/pets' do
post 'Creates a pet' do
tags 'Pets'
consumes 'application/json', 'application/xml'
parameter name: :pet, in: :body, schema: {
type: :object,
properties: {
name: { type: :string },
photo_url: { type: :string },
status: { type: :string }
},
required: [ 'name', 'status' ]
}
response '201', 'pet created' do
let(:pet) { { name: 'Dodo', status: 'available' } }
run_test!
end
response '422', 'invalid request' do
let(:pet) { { name: 'foo' } }
run_test!
end
end
end
path '/api/v1/pets/{id}' do
get 'Retrieves a pet' do
tags 'Pets'
produces 'application/json', 'application/xml'
parameter name: :id, :in => :path, :type => :string
response '200', 'name found' do
schema type: :object,
properties: {
id: { type: :integer, },
name: { type: :string },
photo_url: { type: :string },
status: { type: :string }
},
required: [ 'id', 'name', 'status' ]
let(:id) { Pet.create(name: 'foo', status: 'bar', photo_url: 'http://example.com/avatar.jpg').id }
run_test!
end
response '404', 'pet not found' do
let(:id) { 'invalid' }
run_test!
end
end
end
end
If rswag what tips would you give me?
You need to change the swagger_helper.rb file. Change the file format to JSON. I have attached the screenshot for that one below:
https://i.stack.imgur.com/MzOR9.png

rswag gem does not recognize my parameters in rspec

when running RSpec, in the action of controller,(use byebug or pry)
the specific value like (email or password) did not exist in the request parameters,
and so the result of the test become failed
for more details, see my below code
path '/api/v1/admin/authentications/sign_in' do
post('admin sign_in') do
produces 'application/json'
parameter name: :params, in: :body, schema: {
type: :object,
properties: {
email: { type: :string },
password: { type: :string }
},
required: %w[email password]
}
let(:admin) { create(:admin) }
response('200', 'sign in successfully') do
let(:params) { { email: admin.email, password: '***' } }
run_test!
end
end
end
add consume type for your request:
consumes 'application/json'
I also had the same problem with the latest version of gem rswag. You can change the version of gem to "1.6" to fix it

Resources