Stubbing out Paperclip/ImageMagick in Tests

May 19, 2010 Pivotal Labs

Many people use the ultra popular Paperclip library to handle file attachments in Rails. Unfortunately the Paperclip documentation does not cover how to stub out calls to ImageMagick in your test suite. Without the proper stubs in place a test suite that uses Paperclip will take much, much longer to run.

In the grease your suite presentation by Nick Gauthier it has a slide titled Quickerclip that describes what needs to be done to spend up Paperclip in tests, basically you need to keep it from shelling out to ImageMagick. Alas, the presentation does include code for how to achieve Quickerclip.

As the presentation shows Paperclip.run is the method that needs to be changed. The first parameter passed to Paperclip.run is the ImageMagick command be executed. Paperclip uses the identify and convert commands. The identify command is used to determine the dimensions of an image. The convert command is the really heavy one that does image manipulation and thumbnail generation. Here is a redefinition of Paperclip.run with sensible behavior for tests.

module Paperclip
  def self.run cmd, params = "", expected_outcodes = 0
    case cmd
    when "identify"
      return "100x100"
    when "convert"
      return
    else
      super
    end
  end
end

class Paperclip::Attachment
  def post_process
  end
end

Redefining post_process in Paperclip::Attachment is an optional additional optimization. In Paperclip, post_process eventually calls Paperclip.run("convert") and by short-circuiting the method earlier in the chain we save a few cycles.

About the Author

Biography

More Content by Pivotal Labs
Previous
Standups 5/18/2010 and 5/19/2010: SEO routes
Standups 5/18/2010 and 5/19/2010: SEO routes

Ask for Help "Our site requires crafting URLs in a very particular SEO-friendly way. Rails doesn't s...

Next
ActiveModelListener and AutoTagger become better Ruby citizens
ActiveModelListener and AutoTagger become better Ruby citizens

If you use auto_tagger in conjunction with a continuous integration build you may have noticed that the aut...

Enter curious. Exit smarter.

Register Now