Rails 4回形针FactoryGirl文件上传 [英] Rails 4 Paperclip FactoryGirl file uploading
问题描述
我有一个FactoryGirl:product工厂,它使用fixture_file_upload
设置image
,这是一个回形针附件.
I have a FactoryGirl :product factory that uses fixture_file_upload
to set image
, which is a Paperclip attachment.
image { fixture_file_upload "#{Rails.root}/spec/fixtures/images/product.png", 'image/png' }
fixture_file_upload
可以正常工作,但是,每次测试使用工厂创建新产品时,Paperclip都会在publicproducts/<id>/original.png
中创建一个新文件. 这是问题..每次测试运行时都不能填充文件夹publicproducts
.
fixture_file_upload
works fine, but every time a test creates a new Product using the factory, Paperclip creates a new file in publicproducts/<id>/original.png
. This is the issue.. Filling a the folder publicproducts
on each test run is not acceptable.
我能想到的第一个解决方法是 https://github.com/carrierwaveuploader/carrierwave/wiki/操作方法:-Cleanup-after-your-Rspec-tests
The first workaround I can think of is the solution mentioned in https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-Cleanup-after-your-Rspec-tests
您以其他方式解决了这个问题吗?
Have you solved this problem in another way?
推荐答案
Deep也提到了以下解决方案:
The solution, also mentioned by Deep is to:
- 指定测试环境中的回形针应将文件上传到文件夹
test_uploads
, - 修改factory_girl工厂以上传ex的灯具.
spec/fixtures/images/filename.extension
, - 在
rails_helper.rb
中添加所有清理块
- specify that paperclip in test environment should upload files to folder
test_uploads
, - modify factory_girl factories to upload a fixture from ex.
spec/fixtures/images/filename.extension
, - add an after all cleanup block in
rails_helper.rb
在代码中:
config/environments/test.rb
...
config.paperclip_defaults = {
path: ':rails_root/test_uploads/:class/:id/:attachment/:filename.:extension',
url: ':rails_root/test_uploads/:class/:id/:attachment/:filename.:extension'
}
...
spec/factories/products.rb
image { fixture_file_upload "#{Rails.root}/spec/fixtures/images/product.png", 'image/png' }
rails_helper.rb
...
include ActionDispatch::TestProcess
config.after(:all) do
if Rails.env.test?
test_uploads = Dir["#{Rails.root}/test_uploads"]
FileUtils.rm_rf(test_uploads)
end
end
...
这篇关于Rails 4回形针FactoryGirl文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!