我想测试在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 ::测试:: UploadedFile的:0x0055b544479128>”
而不是实际的文件。
相同的代码适用于控制器测试
尝试使用fixture_file_upload:fixture_file_upload
或者如果你想在工厂里使用它
Rack::Test::UploadedFile.new(File.open(File.join(Rails.root, '/spec/fixtures/images/bob-weir.jpg')))
在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_path
之间添加params: params
,请添加并告诉我。
希望有所帮助!
在rails_helper.rb中
include ActionDispatch::TestProcess
include Rack::Test::Methods
那你几乎没有选择。你可以使用fixture_file_upload助手
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 }
可能对其他用户有用:我遇到了这个问题,因为我在我的规范中错误地使用了get
而不是post
请求。