Rails Rswag Swagger UI无法正确发送标题

问题描述

我将gem rswag用于我的Rails api文档。我的rails API要求所有请求都包括headers['Content-Type']='my-fancy-content-type'headers['Accept']='my-fancy-accept。到目前为止,我已经完成了使用POSTMAN的测试,并且一切正常。我的Rspec测试也全部通过。

http://localhost:3002/api-docs/index.html使用大头UI时。我输入了正确的参数(在本例中为id)和正确的标题,如屏幕截图所示:

swagger UI

似乎没有头发送。控制台显示它正在做curl -X GET "http://localhost:3002/segments/122" -H "accept: */*",没有任何标题

我的spec/swagger_helper.rb设置如下:

require 'rails_helper'

RSpec.configure do |config|
  config.swagger_root = Rails.root.join('swagger').to_s
  config.swagger_docs = {
    'v1/swagger.yml' => {
      openapi: '3.0.1',info: {
        title: 'API V1',version: 'v1'
      },paths: {},servers: [
        {
          url: 'http://{defaultHost}',variables: {
            defaultHost: {
              default: "localhost:#{ENV['PORT']}"
            }
          }
        }
      ]
    }
  }

  config.swagger_format = :yaml
end


我的swagger.yaml看起来像:

---
openapi: 3.0.1
info:
  title: API V1
  version: v1
paths:
  "/segments/{id}":
    get:
      summary: Find segment by id
      tags:
      - Segments
      parameters:
      - name: Accept
        in: header
        required: true
        schema:
          type: string
      - name: Content-Type
        in: header
        required: true
        schema:
          type: string
      - name: id
        in: path
        required: true
        schema:
          type: integer
      responses:
        '200':
          description: success
          content: {}
        '404':
          description: not_found
          content: {}
servers:
- url: http://{defaultHost}
  variables:
    defaultHost:
      default: localhost:3002
securityDeFinitions:
  Content-Type:
    type: string
    description: Content-Type
    name: Content-Type
    in: header

用于生成摇摇欲坠的文档的测试片段是(正常通过):

path '/segments/{id}' do
    get 'Find segment by id' do
      tags 'Segments'
      parameter name: :Accept,in: :header,type: :string,required: true
      parameter name: 'Content-Type',required: true
      parameter name: :id,in: :path,type: :integer
      context 'when record exists' do
        response '200',:success do
          schema type: :object,properties: {
                   content: {
                     id: {type: :string},type: {type: :string},attributes: {
                       id: :integer,...
                     }
                   }
                 }
          run_test! do |response|
            expect(response.status).to eq(200)
            
          end
        end

我尝试在c.swagger_headers = { 'Content-Type' => 'my-fancy-content-type','Accept' => 'my-fancy-accept' }的Rswag :: Api.config里面添加config/initializers/rswag_api.rb,但是没有用(即不发送任何标题)。

在此先感谢您的帮助!

解决方法

在我的spec/swagger_helper.rb中,我不再使用Open API,而是使用Swagger 2.0。所以改变

config.swagger_docs = {
    'v1/swagger.yml' => {
      openapi: '3.0.1',

  config.swagger_docs = {
    'v1/swagger.json' => {
      swagger: '2.0',

现在它可以工作了。