我在我的文本/固定灯/文件填充器中有一个小图像文件,我试图使用外部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
不幸的是,如果我这样做,则结果是无效的请求参数:无效% - 编码,这是有道理的,因为我要发布一个param而不是主体。
如何将上传的文件设置为请求的正文?我可以用Postman发布文件主体,并且它可以很好地工作,但是我想自动进行测试过程。
正确的方法是使用控制器中的代码
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= ...
我使用了此:
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