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

Learn how to keep your Rails apps fast, secure and running in top condition.

The Ruby and Rails worlds move fast, so it can feel like no time at all before your app starts to feel left behind.

Slow pages, memory, new gems, a constant stream of security patches, changing third-party APIs, and growing demands on your server's resources all work tirelessly against your app.

While your app launched with a strong foundation— the latest gems, employing best practices, and developing a thorough test suite—it needs constant attention and maintenance to keep running in top condition.

In Keep Your Ruby on Rails App Healthy, you'll learn about the tools and techniques for keeping your Ruby on Rails app running smoothly, and how to apply them to your apps.

The course delivers a range of practical and actionable lessons to enhance and protect your app right away, from simple, quick–win optimisations and setting up thorough monitoring to reviewing your site's performance, and checking your code against security vulnerabilities current best practices.

“I really enjoyed the book. A lot of quick wins for me to implement and makes me realise I can do more with guard.” –– Ben (@r0_0tKat)

Keep Your Ruby on Rails App Healthy is available as both an email course, and as a premium download edition.

The email course is split up into 7 lessons, delivered to your inbox over the course of a month.

The premium edition is available for instant download in PDF, ePub and Mobi (Kindle) format.

Start Email Course Buy Premium $9 (plus EU VAT)

rails programming tips factory_girl paperclip
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.