问题
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'
params = { file: Rack::Test::UploadedFile.new(path, 'application/pdf', true) }
post v1_product_documents_path, params: params
In the controller, I get a string
"#Rack::Test::UploadedFile:0x0055b544479128>"
instead of the actual file.
The same code works in controller tests
回答1:
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')))
回答2:
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!
回答3:
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
- 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 }
回答4:
Might be useful for other users: I got this problem because I mistakenly used a get
instead of a post
request in my specs.
回答5:
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 } }
来源:https://stackoverflow.com/questions/40796140/how-to-upload-a-file-in-a-rails-rspec-request-spec