Paperclip and Rspec: Stubbing Paperclip/ImageMagick to make specs run faster, but with image resolution validation

I always test my Paperclip stuff. Mostly because quite often, I need to ensure proper images resolution or other image-based conditions. Unfortunately, it takes some time, mostly because ImageMagick is performing resource consuming operations. Each resolution test needs to get valid image to determine width and height. After that, Paperclip will try to create all the thumbs and save them. This takes a lot of time! Luckily there's a Quickerclip that stubs Paperclip methods, allowing it to run faster. There's one small issue with this code: it stubs the image, so there's no way to test resolution validations. In order to make it work, but without any additional callbacks and without images converting, we need to stub two things:

First the Paperclip.run method:

# We stub some Paperclip methods - so it won't call shell slow commands
# This allows us to speedup paperclip tests 3-5x times.
module Paperclip
  def self.run cmd, params = "", expected_outcodes = 0
    cmd == 'convert' ? nil : super
  end
end

This will ignore convert command, so thumbnails won't be created on save.

Also we need to stub the Paperclip::Attachment.post_process:

class Paperclip::Attachment
  def post_process
  end
end

Don't forget to add this to your spec_helper or test_helper file!

After that, your tests/specs should run 3-5x times faster (it depends on how heavily you app is Paperclip based.

UPDATE FOR PAPERCLIP > 3.5.2
For Paperclip newer than 3.5.2 please use code presented below:

module Paperclip
  def self.run cmd, arguments = "", interpolation_values = {}, local_options = {}
    cmd == 'convert' ? nil : super
  end
end

class Paperclip::Attachment
  def post_process
  end
end

Categories: Rails, Ruby, Software

1 Comment

  1. Thanks a lot, exactly what I was looking for!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Copyright © 2024 Closer to Code

Theme by Anders NorenUp ↑