[我正在使用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
参数,并且没有任何变化。我已经尝试了100万种组合,结果始终相同,但我不知道发生了什么。
控制器期望的params
是data[attributes][file]
。
有人可以帮我吗?
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