我目前正在测试上传的文件是否与原始文件相同。 api 要求上传正文是二进制的,而不是 multipart/form-data。
这是规格:
it "uploads" do
fixture_path = Rails.root.join("spec/fixtures/")
fixture_file = fixture_path.join("landscape.jpg")
file = Rack::Test::UploadedFile.new(fixture_file, "image/jpeg", :binary)
post api_upload_upload_path, file, header
assert_response :success
end
当我运行规范时,它失败了:
Failures:
1) Api::V1::UploadController uploads
Failure/Error: post api_upload_upload_path, file, company_header
ArgumentError:
invalid %-encoding (These are bad characters
如何解决这个问题? 或者,有没有更好的方法来测试这种动作?
我已经弄清楚了。这是因为浏览器很难发布图像。 AngularJS 将其放入 multipart/form-data 中。
很高兴您找到了解决方案!在 Rails 6+ 中,您还应该能够通过在
body
上设置 #post
参数来实现二进制上传:
file = file_fixture('landscape.jpg')
post api_upload_path, body: file.binread, as: :binary