15 October 2010 · About 1 minute read

Rails 3: How to Simulate Paperclip Attachments With FactoryGirl

In developing the next phase of markstocks.com, I needed to simulate a file upload attribute in my FactoryGirl factories. A quick Google revealed some promising code, but everything out there was based on Rails 2.

There’s been a lot of changes in Rails 3, so using what I found, I tweaked the code to work in my Rails 3 factories. I’ve also posted this code as a gist forked from the original Rails 2 version on Github.

```ruby# spec/spec_helper.rb

Support for Paperclip factories (add this before you load your factory definitions)

include ActionDispatch::TestProcess

ruby# spec/support/factory_attachment.rb

Factory.class_eval do

def attachment(name, path, content_type = “image/jpg”)

path_with_rails_root = "#{Rails.root}/#{path}"

uploaded_file = fixture_file_upload(path_with_rails_root, content_type)

add_attribute name, uploaded_file



```ruby# spec/factories/photos.rb

Factory.define :photo do p

# Given a Photo model with has_attached_file :image

p.attachment :image, “spec/support/sample_photo.jpg”



  1. Original Gist
  2. APIDock.com
Chris Blunt
Chris Blunt @cblunt
Chris is the founder of Plymouth Software. As well as code and business, he enjoys being a Dad, swimming, and the fine art of drinking tea.