CarrierWave 多文件上传 Rails 单元测试

CarrierWave Multiple File Upload Rails Unit Testing

我一直在用 Carrierwave 敲我的头。通过将 Carrierwave 的主分支添加到我的 Gemfile,我终于能够让载波上传多个文件:

gem 'carrierwave', github:'carrierwaveuploader/carrierwave'

我将它用于一个名为 Product 的模型,然后我就这样做了。 Product.rb

class Product < ActiveRecord::Base
  mount_uploaders :avatar, ProductUploader
end

而且我基本上遵循了规则并且能够上传多个文件,同时让每个文件在我的 products_controller.rb 中迭代创建方法并为每个上传的文件创建一个新的 Product 实例。

现在。测试来了。以前,当只上传一个文件时,我可以使用

test "should create product" do
  login
  excel_filename = 'files/product_create_test.xls'
  file = fixture_file_upload(excel_filename, 'application/excel')
  assert_difference('Product.count') do
    post :create, product: {:file_url => file}
  end

但是现在,添加了上传多个文件的功能后,fixture_file_upload好像不能正常使用了。 我收到此错误:

 ProductsControllerTest#test_should_create_product:
    ArgumentError: wrong number of arguments (2 for 0)
        test/controllers/products_controller_test.rb:54:in `block (2 levels) in <class:ProductsControllerTest>'
        test/controllers/products_controller_test.rb:53:in `block in <class:ProductsControllerTest>'

我不确定如何解决这个问题。就像我说的,当我

 gem 'carrierwave' 

之前的测试工作正常。有没有人遇到过这个?

这就是问题所在。为了使我的夹具文件上传不会实际保存在我的测试环境中,我遵循了这篇文章,http://jeffkreeftmeijer.com/2014/using-test-fixtures-with-carrierwave/#comment_768

此处它告诉您将以下内容添加到您的 test_helper 文件

class CarrierWave::Mount::Mounter
  def store!
    # Not storing uploads in the tests
  end
end

这实际上告诉您的测试环境不要将上传的装置存储在任何地方。无论如何,这段代码在添加用于多个文件上传的载波主分支时运行不佳。我最终取消了它的注释,尽管它存储了上传的文件,但我的测试通过了。