【问题标题】:How to upload a file in a Rails Rspec request spec如何在 Rails Rspec 请求规范中上传文件
【发布时间】:2016-11-25 00:27:37
【问题描述】:

我想在 Rails Rspec 请求测试中测试上传文件。我正在使用 Paperclip 进行资产存储。

我试过了:

path = 'path/to/fixture_file'
params = { file: Rack::Test::UploadedFile.new(path, 'application/pdf', true) }
post v1_product_documents_path, params: params

在控制器中,我得到一个字符串

"#Rack::Test::UploadedFile:0x0055b544479128>"

而不是实际的文件。

相同的代码在控制器测试中工作

【问题讨论】:

    标签: ruby-on-rails rspec ruby-on-rails-5


    【解决方案1】:

    尝试使用 fixture_file_uploadfixture_file_upload

    或 如果您想在工厂中使用它

     Rack::Test::UploadedFile.new(File.open(File.join(Rails.root, '/spec/fixtures/images/bob-weir.jpg')))
    

    【讨论】:

    • fixutre_file_upload 在后台使用Rack::Test::UploadedFile,所以这通常是相同的。
    【解决方案2】:

    在 rails_helper.rb 中做

    include ActionDispatch::TestProcess
    include Rack::Test::Methods
    

    那么你有几个选择。 1.可以使用fixture_file_uploadhelper

      let(:file) { fixture_file_upload('files/image.jpg') }
      it 'it should work' do
        post some_path, params: { uploads: { file: file } }
      end
    
    1. 您可以使用上传的文件,但您必须提供完整路径
      let(:file) { Rack::Test::UploadedFile.new(Rails.root.join('spec',
      'fixtures', 'blank.jpg'), 'image/jpg') }
      let(:params) { { attachment: file, variant_ids: ['', product.master.id] } }
      let(:action) { post :create, product_id: product.slug, image: params }
    

    【讨论】:

    • 我认为这与 RSB 的回答没有任何实际区别。
    【解决方案3】:

    describe 块下,包含这些模块

    include Rack::Test::Methods
    include ActionDispatch::TestProcess
    

    现在尝试运行规范

    path = 'path/to/fixture_file'
    params = { "file" => Rack::Test::UploadedFile.new(path, 'application/pdf', true) }
    post v1_product_documents_path, params: params
    

    另外,我猜你忘了在v1_product_documents_pathparams: params 之间添加,,请添加并告诉我。

    希望有帮助!

    【讨论】:

    • 这两个包括似乎没有帮助(我之前尝试过)。您是否能够在 Rails 请求规范中使用它?
    • @hirowatari 你确实把包含在describe 块中?
    【解决方案4】:

    对于 rails 6,无需包含,只需 fixture_file_upload。如果你使用 spec/fixtures/files 文件夹来存放灯具,你可以使用 file_fixture helper

    let(:csv_file) { fixture_file_upload(file_fixture('file_example.csv')) }
    
    subject(:http_request) { post upload_file_path, params: { file: csv_file } }
    

    【讨论】:

      【解决方案5】:

      可能对其他用户有用:我遇到这个问题是因为我在规范中错误地使用了 get 而不是 post 请求。

      【讨论】:

        【解决方案6】:

        对于其他人在实施上述批准的解决方案后仍然在控制器中获得类似 "#Rack::Test::UploadedFile:0x0055b544479128>" 的内容,我通过将我的 content-type 标头更改为 'application/x-www-form-urlencoded' 来解决此问题,以便接受表单数据。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-28
          • 2018-10-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多