Tim Riley

Machinist and Paperclip

July 25th 2009 — Sydney, Australia

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!

Tim Riley

Hi, I'm Tim Riley. I'm a web developer based in Canberra, Australia, where I work at a small design studio called Icelab. This is my blog, where I can share with you the things I learn as I go about building products for the web.

What I Build

Recent Presentations

  1. Facebook Authentication with OAuth
  2. JavaScript Testing with Capybara and Cucumber
  3. Using Titanium to Build Mobile Apps with JavaScript (audio)
  4. An Introduction to Sinatra
  5. Building your Capistrano Recipe Book