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
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
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 }
Might be useful for other users: I got this problem because I mistakenly used a get
instead of a post
request in my specs.
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!
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 } }
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')))