我正在尝试设置 Apivore Gem 来测试我的 API 上的 Swagger 文档。但是我很难理解如何将内容作为 JSON 发送到正文中。
Swagger 文档
swagger: '2.0'
info:
version: "api-test-env"
title: 'Prototype API'
description: 'Testing out Swagger and building a proof of concept.'
host: virtserver.swaggerhub.com
schemes:
- https
produces:
- application/json
securityDefinitions:
Bearer:
type: apiKey
name: Authorization
in: header
paths:
/oauth/token:
post:
consumes:
- application/json
tags:
- Account
parameters:
- in: body
name: Credentials
description: 'User login'
schema:
type: object
required:
- grant_type
- username
- password
properties:
grant_type:
type: string
username:
type: string
password:
type: string
responses:
200:
description: 'User logged in successfully'
schema:
type: object
properties:
access_token:
type: string
description: 'Authorization access token'
example: '0ee0e77afbdd6fcaa0920a0416d5043aee9a21ca75920cda7d2b1be0d9f40885'
token_type:
type: string
description: 'Authorization token type'
example: 'Bearer'
expires_in:
type: integer
description: 'Timestamp expiration time'
example: 3600
refresh_token:
type: string
description: 'Refresh authorization token'
example: 'ed1307dde23acbb440d6f31520f7d3c8de099e72b04eb1542008ca139fca6364'
created_at:
type: integer
description: 'Timestamp created at time'
example: 1519312812
带有 Apiore 测试的 RSpec
require 'rails_helper'
RSpec.describe 'the API', type: :apivore, order: :defined, focus: true do
subject { Apivore::SwaggerChecker.instance_for('/docs/swagger.json') }
context 'has valid paths' do
Fabricate(:user, email: '[email protected]', password: 'abc123', password_confirmation: 'abc123')
let(:credentials) { { 'grant_type' => 'password', 'username' => '[email protected]', 'password' => 'abc123' } }
let(:params) do
{
'_headers' => { 'accept' => 'application/json', 'content-type' => 'application/json' },
'_data' => credentials.to_json
}
end
specify do
expect(subject).to validate(
:post, '/oauth/token', 200, params
)
end
end
context 'and' do
it 'tests all documented routes' do
expect(subject).to validate_all_paths
end
end
end
错误信息
Failures:
1) the API has valid paths should validate that post /oauth/token returns 200
Failure/Error: expect(subject).to validate(
Path /oauth/token did not respond with expected status code. Expected 200 got 401
Response body:
{
"error": "invalid_grant",
"error_description": "The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client."
}
# ./spec/requests/api_swagger_spec.rb:19:in `block (3 levels) in <top (required)>'
但是我尝试使用 Postman 获取令牌并工作。如果凭据内容或凭据密钥错误,则会出现此错误消息。
要解决此问题,只需将这一行从...
Fabricate(:user, email: '[email protected]', password: 'abc123', password_confirmation: 'abc123')
... 至
let!(:user) { Fabricate(:user, email: '[email protected]', password: 'abc123', password_confirmation: 'abc123') }
这样,它将在数据库中保存用户的持久性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句