How to upload a file to the Rails Rails specification

I want to check file upload in a Rails Rails test. I use Paperclip to store assets.

I tried:

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

In the controller, I get the line

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

instead of the actual file.

The same code works in controller tests

+10
ruby-on-rails ruby-on-rails-5 rspec
source share
5 answers

try using fixture_file_upload : fixture_file_upload

or if you want to use this in a factory

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

In the describe block enable 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 think you forgot to add , between v1_product_documents_path and params: params , add this and let me know.

Hope this helps!

+3
source share

In rails_helper.rb do

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

Then you have several 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 the downloaded file, but you need to specify the 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 }

+1
source share

For rails 6. If you use the spec/fixtures/files folder for fixtures, you can use the file_fixture

eg

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

May be useful for other users: I had this problem because I mistakenly used get instead of the post request in my specs.

-one
source share

All Articles