【问题标题】:Speed up image processing of Paperclip in Acceptance Tests在验收测试中加快回形针的图像处理
【发布时间】:2013-09-04 04:02:28
【问题描述】:

在运行capybara 功能规范时,我可以看到很多由factory_girl 填充的慢速出厂通知。我认为,这些慢工厂的东西严重减慢了功能规格,甚至功能规格也是固有的慢规格。然后我进行了一些检查,发现大部分慢工厂是由paperclip引起的。我们在这里有使用回形针的模型:

FactoryGirl.define do
  factory :asset do
    image Rails.root.join('spec/fixtures/sample.jpg').open
  end
end

所以我想知道是否有类似paperclip 的测试模式来加快测试速度。我在这里有一个简单的解决方案:只需复制原始文件而不是实际裁剪它。

【问题讨论】:

    标签: ruby-on-rails performance rspec paperclip capybara


    【解决方案1】:

    您可以在工厂设置回形针图像字段,这将导致回形针甚至不尝试处理图像:

    factory :asset do        
      # Set the image fields manually to avoid uploading / processing the image
      image_file_name { 'test.jpg' }
      image_content_type { 'image/jpeg' }
      image_file_size { 256 }
    end
    

    【讨论】:

    • 感谢您的帮助。这很好,但我需要上传路径中存在真实图像,例如public/system/assets/images/000/000/001/medium/test.jpg。如果请求图像时出现 404,则功能规范将失败。
    • 您仍然可以将 image_file_name 指向 Rails.root.join('spec/fixtures/sample.jpg')。
    • 我需要所有原始的,大,中,小图片都存在于他们的目录中。我认为这种方法不会生成这些文件。
    • 谢谢,您将我的测试速度提高了 100 倍 :)
    【解决方案2】:

    我找到了实现这一点的方法,请看这段代码:

    FactoryGirl.define do
      factory :asset do
        image_file_name { 'sample.jpg' }
        image_content_type 'image/jpeg'
        image_file_size 256
    
        after(:create) do |asset|
          image_file = Rails.root.join("spec/fixtures/#{asset.image_file_name}")
    
          # cp test image to direcotries
          [:original, :medium, :thumb].each do |size|
            dest_path = asset.image.path(size)
            `mkdir -p #{File.dirname(dest_path)}`
            `cp #{image_file} #{dest_path}`
          end
        end
      end
    end
    

    在创建钩子后手动cp 将测试图像添加到 factory_girl 中的真实资产图像路径。它就像一个魅力。

    【讨论】:

    • 仅供他人参考。我只能使用 after(:build) 回调,但它无法访问 id。通过向 id 添加一个序列来解决这个问题:sequence(:id){|n|n}
    猜你喜欢
    • 1970-01-01
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多