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.
# spec/spec_helper.rb
...
# Support for Paperclip factories (add this before you load your factory definitions)
include ActionDispatch::TestProcess
# 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
end
end
# 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"
end
References
👋 Thanks for reading - I hope you enjoyed this post. If you find it helpful and want to support further writing and tutorials like this one, please consider supporting my work with a coffee!
Support ☕️