Rails 5 File POST 文件作为 Minitest 中的正文

Rails 5 File POST file as body in Minitest

我的 text/fixtures/filesfolder 中有一个小图像文件,我正试图用它来调用外部 API。它是一个 JPG。我正在尝试在我的控制器测试中使用此方法对其进行测试

 test 'post image to external API' do
    binding.pry
    image = fixture_file_upload('files/simple_image.jpg', 'image/jpg')
    post '/api/services/image_processor', params: {body: image}
    assert_response :success
  end

不幸的是,如果我这样做,结果是无效的请求参数:无效的 %-编码,这是有道理的,因为我post输入的是参数而不是主体。

如何将上传的文件设置为请求的正文?我可以使用 postman post 文件主体,它工作得很好,但我想自动化测试过程。

我用过这个:

image = fixture_file_upload('files/simple_file.jpg', 'image/jpg', :binary)
post '/api/services/image_processor', params: image.tempfile, headers: { 'CONTENT-TYPE': 'image/jpg' }
assert_response :success

正确的方法是在控制器中使用以下代码

a) 如果将文件传递给需要路径的方法(如 CSV 解析器)

params[:file].path

b) 或者如果你需要文件内容的话这个

params[:file].read

然后在你的测试中

file = fixture_file_upload('path/to/some/file.csv')
post '/api/endpoint',
     params: { file: file },
     headers: { 'content-type': 'multipart/form-data' }

这样在params你会发现一个正常工作的文件上传

<ActionController::Parameters {"file"=>#<ActionDispatch::Http::UploadedFile:0x007ff3f1ea8e80 @tempfile= ...