Machinist and Paperclip

Once you’ve found a comfortable fixture replacement for your tests, there is no going back. For many, that’s something like Factory Girl. For me, it is Pete Yandell’s Machinist. So when I wanted to write some Cucumber scenarios for a model using Paperclip for file attachments, I definitely needed a factory for creating it!

In Machinist, building factories (called blueprints) is easy for standard ActiveRecord attributes and associations. Check out the comprehensive README in the repository. Here is the start of a blueprints.rb file:

require 'faker'

Sham.title { Faker::Lorem.sentence }

AttachedDocument.blueprint do
  title
end

As it turns out, it is equally easy to add support for models using Paperclip. Say our model looks like this:

class AttachedDocument < ActiveRecord::Base
  has_attached_file :document
end

Then your blueprint should incorporate the attached file like this:

require 'faker'

Sham.title { Faker::Lorem.sentence }
Sham.document { Tempfile.new('the attached document') }

AttachedDocument.blueprint do
  title
  document
end

Using a Tempfile instance to represent the paperclip attachments works without a hitch, and the implementation of Tempfile will ensure there are no file duplicates. It will also mean that the other methods that paperclip sets up (such as document_file_name, document_content_type and document_file_size) are all accessible on the generated object. Now get going and test!

© 2008-2024 Tim Riley. All rights reserved.