Rails 4 Paperclip FactoryGirl file uploading

为君一笑 提交于 2019-12-04 13:18:18

问题


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 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.

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?


回答1:


The solution, also mentioned by Deep is to:

  • 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

In code:

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
  ...


来源:https://stackoverflow.com/questions/31650949/rails-4-paperclip-factorygirl-file-uploading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!