Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jeffrafter/419014 to your computer and use it in GitHub Desktop.
Save jeffrafter/419014 to your computer and use it in GitHub Desktop.
factory_girl attachments for paperclip
require 'action_controller/test_process'
# Paperclip attachments in factories, made easy based on technicalpickles
Factory.class_eval do
def attach(name, path, content_type = nil)
if content_type
add_attribute name, ActionController::TestUploadedFile.new("#{RAILS_ROOT}/#{path}", content_type)
else
add_attribute name, ActionController::TestUploadedFile.new("#{RAILS_ROOT}/#{path}")
end
end
end
Factory.sequence :badge do |n|
"name#{n}"
end
Factory.define :badge do |badge|
badge.name { Factory.next :badge }
badge.active { true }
badge.description { "You get this when you are awesome" }
badge.tags { "cool awesome" }
badge.site { |badge| badge.association(:site) }
badge.attach ( "image", "test/fixtures/flower.png", "image/png" )
end
@sr3d
Copy link

sr3d commented Jun 14, 2010

awesome, just exactly what I'm looking for!

Thanks!

@jeffrafter
Copy link
Author

Awesome! Was inspired by some critical forum postings from Josh Nicols/techpickles

@sr3d
Copy link

sr3d commented Jun 16, 2010

For Rails 3, your gist actually doesn't work. After looking at the Rails code, this code works:

Factory.define :contacts_short_csv, :class => 'CsvFile' do |f|
  include ActionDispatch::TestProcess
  f.csv   { fixture_file_upload( 'files/contacts_short.csv.upload', 'text/csv') }
  f.account_id { 1 }
end

My model is

class CsvFile < ActiveRecord::Base
  include Paperclip
  has_attached_file :csv
end

The CSV file is actually under test/fixtures/files/ and since they are not real fixture data, but actual CSV data for testing the data import process, I had to rename them as .csv.upload otherwise Rails's test will try to populate the test databases with them (and fail miserably)

I'm using Rails 3b4, with latest paperclip 61f74...eed69-master

@insane-dreamer
Copy link

You can simplify further by just adding "include ActionDispatch::TestProcess" to test_helper.rb, and then just using the following in your factory

f.field_name { fixture_file_upload 'filename', 'mimetype' }

@mhayes
Copy link

mhayes commented Oct 13, 2011

I realize this is a pretty old post, but wasn't sure if anyone here has run into an issue when using S3 for storage. I'm using the code mentioned by sr3d, but am getting AWS::S3::RequestTimeTooSkewed in my test results when attempting to use a factory that contains an "upload" file.

@s9gf4ult
Copy link

Dont work for Rails 4.1

.rvm/gems/ruby-2.1.0@banners/gems/factory_girl-4.4.0/lib/factory_girl/definition_proxy.rb:42:in `add_attribute': wrong number of arguments (4 for 1..2) (ArgumentError)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment