How to upload a file in a Rails Rspec request spec

前端 未结 5 2193
没有蜡笔的小新
没有蜡笔的小新 2021-02-19 03:20

I want to test uploading a file in a Rails Rspec request test. I\'m using Paperclip for asset storage.

I\'ve tried:

path = \'path/to/fixture_file\'
para         


        
相关标签:
5条回答
  • 2021-02-19 03:25

    In rails_helper.rb do

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

    Then you have few options. 1. You can use fixture_file_upload helper

      let(:file) { fixture_file_upload('files/image.jpg') }
      it 'it should work' do
        post some_path, params: { uploads: { file: file } }
      end
    
    1. You can use Uploaded file but you have to give full path
      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 }
    
    0 讨论(0)
  • 2021-02-19 03:35

    Might be useful for other users: I got this problem because I mistakenly used a get instead of a post request in my specs.

    0 讨论(0)
  • 2021-02-19 03:41

    Under describe block, include these modules

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

    Now try running the specs

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

    Also, I guess you forgot to add , between v1_product_documents_path and params: params, please add that and let me know.

    Hope that helps!

    0 讨论(0)
  • 2021-02-19 03:42

    For rails 6 no need to do includes, just fixture_file_upload. If you are using spec/fixtures/files folder for fixtures you can use 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 } }
    
    0 讨论(0)
  • 2021-02-19 03:47

    try to use fixture_file_upload: fixture_file_upload

    or if you wanted to use this in a factory

     Rack::Test::UploadedFile.new(File.open(File.join(Rails.root, '/spec/fixtures/images/bob-weir.jpg')))
    
    0 讨论(0)
提交回复
热议问题