Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

  • Blog Navigation
Stubbing out Paperclip/ImageMagick in Tests

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 is the method that needs to be changed. The first parameter passed to 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 with sensible behavior for tests.

module Paperclip
  def cmd, params = "", expected_outcodes = 0
    case cmd
    when "identify"
      return "100x100"
    when "convert"

class Paperclip::Attachment
  def post_process

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

  • Hey Rob,

    Here is our quickerclip implementation:

    Same idea, but I patch it further down. Also you’ll note that when it tries to make a thumbnail I actually copy a fixture file over so it thinks there’s a real file on the filesystem.

    How much time did it save you?


  • Rob Olson

    Hey Nick,

    Thanks for sharing that code. I have to say I was quite confused when reading the slides and it mentioned Quickerclip but I couldn’t find it anywhere.

    I did notice that you copy the fixture file over to create the thumbnail. I neglected to do this on purpose because none of my tests depend on the thumbnails. Since I started with that I am not sure how much time it saved.

Share This