ruby 如何在rails中测试二进制上传文件?

vngu2lb8  于 11个月前  发布在  Ruby
关注(0)|答案(2)|浏览(116)

我目前正在测试,如果上传的文件是相同的原始文件。API要求上传主体为二进制,而不是multipart/form-data。
这就是spec:

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

当我运行spec时,它失败了:

Failures:

  1) Api::V1::UploadController uploads
     Failure/Error: post api_upload_upload_path, file, company_header
     ArgumentError:
       invalid %-encoding (These are bad characters

如何解决这一问题?或者,有没有更好的方法来测试这种行为?

cwxwcias

cwxwcias1#

我想好了这是因为浏览器很难发布图像。AngularJS将其放入multipart/form-data中。

6gpjuf90

6gpjuf902#

很高兴你找到了解决方案!在Rails 6+中,你也可以通过在#post上设置body arg来实现二进制上传:

file = file_fixture('landscape.jpg')
post api_upload_path, body: file.binread, as: :binary

相关问题