rswag 规范中的 GET 请求 JSON 正文参数

问题描述 投票:0回答:1

问题

如何编写一个 rswag 规范,将

my_field: 'my_value'
传递到我的控制器的
params
中以进行 GET 请求?

初步尝试

config/routes.rb:

Rails.application.routes.draw do
  namespace :api do
    resources :my_tests
  end
end

应用程序/控制器/api/my_tests_controller.rb

class Api::MyTestsController < Api::BaseController
  def index
    render json: do_something_with(params) # expect `params[:my_field] == 'my_value'`
  end
end

spec/api/my_tests/index_spec.rb:

RSpec.describe 'Test', type: :request do
  context 'on openapi spec' do
    let(:Authorization) { bearer_token }

    path '/api/my_tests' do
      get 'Test' do
        consumes 'application/json'
        produces 'application/json'
        security [bearerAuth: {}]
        parameter name: :my_field, in: :body, type: :string

        response '200', 'Test' do
          let(:my_field) { 'my_value' }

          run_test!
        end
      end
    end
  end
end

产生无效

params
:

{
  "\"my_value\"": nil,
  controller: "api/my_tests",
  action: "index",
  my_test: {}
}

尝试应用适用于 POST 的解决方案

https://github.com/rswag/rswag/issues/290 中找到的解决方案适用于 POST,但不适用于 GET。

spec/api/my_tests/index_spec.rb:

RSpec.describe 'Test', type: :request do
  context 'on openapi spec' do
    let(:Authorization) { bearer_token }

    path '/api/my_tests' do
      get 'Test' do
        consumes 'application/json'
        produces 'application/json'
        security [bearerAuth: {}]
        parameter name: :body, in: :body, schema: {
          type: :object,
          properties: {
            my_field: { type: :string },
          },
        }

        response '200', 'Test' do
          let(:body) { { my_field: 'my_value' } }

          run_test!
        end
      end
    end
  end
end

产生无效

params
:

{
  "{\"my_field\":\"my_value\"}": nil,
  controller: "api/my_tests",
  action: "index",
  my_test: {}
}

如果请求是 POST 而不是 GET,则会产生有效的

params
:

{
  "my_field": "my_value", # <- This is the field I want
  "controller": "api/my_tests",
  "action": "foo",
  "my_test": {
    "my_field": "my_value"
  }
}
ruby-on-rails rspec rswag
1个回答
0
投票

不幸的是 rswag 不支持使用 body 的此类 GET 请求

您可以定义这样的助手来修补请求:

def send_request(metadata)
  request = Rswag::Specs::RequestFactory.new.build_request(metadata, self)

  if request[:verb] == :get &&
      request[:payload].present? &&
      request[:headers]['CONTENT_TYPE'] == 'application/json'
    request[:payload] = JSON.parse(request[:payload])
  end

  send(
    request[:verb],
    request[:path],
    params: request[:payload],
    headers: request[:headers]
  )
end

并这样使用它

it 'returns 200' do |example|
  send_request(example.metadata)
end
© www.soinside.com 2019 - 2024. All rights reserved.