【问题标题】:Following JSON Api with rswag使用 rswag 跟随 JSON Api
【发布时间】:2020-05-20 11:46:52
【问题描述】:

我正在使用 rswag 测试一个相当常见的 RubyOnRails JSON Api 应用程序,但我无法弄清楚我将文件上传到端点的一个相当常见的情况。

端点需要请求正文中的常用data 属性和包含二进制文件的file 属性,我无法使rswag 生成具有正确参数的请求。

  path '/documents' do
    post 'Creates a document' do
      tags 'Documents'
      consumes 'multipart/form-data'
      produces 'application/vnd.api+json'

      parameter name: 'data',
                description: 'Whatever',
                attributes: {
                  schema: {
                    type: :object,
                    properties: {
                      file: { type: :binary },
                    },
                  },
                }

      response '201', 'success' do
        let(:data) do
          {
            attributes: {
              file: Rack::Test::UploadedFile.new($REALARGS),
            },
          }
        end

        schema "$ref": '#/definitions/post_document_responses/201'

        run_test! do |_example|
          # ACTUAL TEST
        end
      end
    end
  end

还有一些其他更简单的参数(例如授权)是正确生成的,我确定rswag 被正确连接。 我看到的请求没有参数,我可以删除 data 参数并且没有任何变化。我已经尝试了一百万种组合,结果总是一样,但我不知道发生了什么。

控制器期望的paramsdata[attributes][file]

谁能帮帮我?

【问题讨论】:

    标签: ruby-on-rails rspec json-api rswag


    【解决方案1】:

    parameter 块需要指定插入的位置。有一个example spec,我在其中找到了对:formData 的引用,事实证明必须设置(即你不能使用:body,它只会发送一个空请求)。

    经过一番折腾后,我设法让您的示例使用表单数据中的嵌套属性:

    path '/documents' do
      post 'Creates a document' do
        tags 'Documents'
        consumes 'multipart/form-data'
        produces 'application/vnd.api+json'
    
        parameter name: 'data[attributes][file]',
                  description: 'Whatever',
                  in: :formData,
                  attributes: {
                    schema: {
                      type: :object,
                      properties: {
                        file: { type: :binary },
                      },
                    },
                  }
    
        response '201', 'success' do
          let(:"data[attributes][file]") { Rack::Test::UploadedFile.new(Rails.root.join("spec/requests/api/v1/documents_post_spec.rb")) }
          end
    
          schema "$ref": '#/definitions/post_document_responses/201'
    
          run_test! do |_example|
            # ACTUAL TEST
          end
        end
      end
    end
    

    【讨论】:

      【解决方案2】:

      如果您需要发送包含文件的对象数组,您可以执行以下操作:

      parameter name: 'documents', in: :formData, type: :array, required: true
      
      let(:documents) do
        [
          {
           file: file_1,
           name: '...' 
          },
          {
           file: file_2,
           name: '...'
          }
        ]
      end
      

      【讨论】:

        猜你喜欢
        • 2020-03-13
        • 2018-11-25
        • 1970-01-01
        • 1970-01-01
        • 2012-02-25
        • 2016-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多