Room 118 Solutions - Web Application Development & Programming

Stubbing Paperclip During Testing


For those of you working with the wonderful paperclip gem, you probably know how slow it can make your test suite. Hitting the FS in every test that creates an object that requires an attachment is slow and unnecessary. Here’s what we’re doing to keep Paperclip from actually saving any files we pass to it:

module Paperclip
  class Attachment
    def save
      @queued_for_delete = []
      @queued_for_write = {}
      true
    end
    
  private
    def post_process_styles
      true
    end
  end
end


class File
  def to_tempfile
    Class.new do
      def size
        # We're using this because it's the size of our sample Rails image, although it doesn't matter for us.
        # If you're not validating the attachment size, any integer should work for you.
        6646
      end
      def read
        ""
      end
    end.new
  end
end

Update for Paperclip 3.0:
There were some significant changes in Paperclip 3.0, you should now use something like this:

module Paperclip
  class Attachment
    def save
      @queued_for_delete = []
      @queued_for_write = {}
      true
    end

  private
    def post_process
      true
    end
  end

  # This is only necessary if you're validating the content-type
  class ContentTypeDetector
  private
    def empty?
      false
    end
  end
end

Just make sure that’s loaded somewhere before your tests run, we’re using RSpec, so we stuck it in spec/support. Our test suite went from taking a painful 90 seconds to run, down to a blazingly fast 10!

Happy (fast) testing!

Jim

Jim Ryan

About Jim Ryan

Jim has been working with computers for as long as he can remember. He started programming when he was 12, and developed his first web application for hire when he was 16. Jim is as adept with hardware as he is with software. He's worked with countless languages on a variety of platforms, from gaming consoles to Android handsets to desktop applications, but his first and true love will always be the Web. For Jim, coding is more than a hobby or a job, it's his passion.

When he's not at his computer (which is rare), Jim's exploring Manhattan or enjoying a nice (gluten-free) meal with friends. He loves meeting new people, whether it be at home or when traveling the globe. Jim tries to learn something new everyday.

View all posts by Jim Ryan →