José Galisteo Ruiz

26/11/2010

Rails 2, Paperclip y Factory Girl

Para poder testear modelos con ficheros en Rails 2, Factory Girl y Paperclip (o cualquier otro sistema supongo), encontré este pequeño método, vi varios, pero algunos eran antiguos o para Rails 3.

Lo puedes pegar en el propio fichero de factories.rb o en el test_helper.rb:

require 'action_controller/test_process'
Factory.class_eval do
  def attachment(name, path, content_type = nil)
    path_with_rails_root = "#{RAILS_ROOT}/#{path}"
    uploaded_file = if content_type
                      ActionController::TestUploadedFile.new(path_with_rails_root, content_type)
                    else
                      ActionController::TestUploadedFile.new(path_with_rails_root)
                    end

    add_attribute name, uploaded_file
  end
end

Luego en tu ‘¿constructor?’ usar el método attachment:

Factory.define :banner do |b|
  b.url  "http://example.com"
  b.attachment(:image, "test/fixtures/flowers.jpg", "image/jpeg")
end
blog comments powered by Disqus