20

Hello i need to build up Factory for my model, for example

Factory.define :farm do |f|
  f.name { Factory.next :name }
  f.harvest '3'
  f.offers 'Random'
  f.latitude '43'
  f.longitude '-70'
  f.about 'We rocks!'
  f.logo { Factory.next :logo } # this doesn't work
end

For now im just pass string "#{n}.jpg" into my logo field and this dont work, how to evalute this field? Im using CarrierWave for uploading.

Petya petrov
  • 2,153
  • 5
  • 23
  • 35

2 Answers2

35

You need to include ActionDispatch::TestProcess in your factory (Rails 3), and use the fixture_file_upload helper:

include ActionDispatch::TestProcess

FactoryGirl.define do
  factory :image do
    title "Example image"
    file { fixture_file_upload("files/example.jpg", "image/jpeg") }
  end
end

Also be sure to create an example file at test/fixtures/files/example.jpg, otherwise you will get an error that the file does not exist.

Adrian Macneil
  • 13,017
  • 5
  • 57
  • 70
  • It seems kind of terrible to rely on the existence of an external file during a unit test. Is there anyway to completely stub or encapsulate the file? – James McMahon Dec 19 '13 at 14:31
  • 1
    There's nothing terrible about having a test fixture file. As long as you check it into source control it will always be there to run your tests on. – Adrian Macneil Dec 19 '13 at 20:41
  • Yeah terrible is hyperbolic, sorry. Just wanted to know if there was an alternative. – James McMahon Dec 20 '13 at 01:15
25

If you don't want to include ActionDispatch::TestProcess you can add files like this,

Factory.define :brand do |f|
  f.name "My Brand"
  f.description "Foo"
  f.logo { Rack::Test::UploadedFile.new(File.join(Rails.root, 'spec', 'support', 'brands', 'logos', 'logo_image.jpg')) }
end

Then just include the file at that given path, in this case it would be spec/support/brands/logos/logo_image.jpg

This is how they suggest doing it on their wiki https://github.com/jnicklas/carrierwave/wiki/How-to%3A-Use-test-fixtures

Ryan
  • 9,340
  • 5
  • 39
  • 42
  • 2
    You should use Rack::Test::UploadedFile, because strong parameters won't pass File type. – sheerun Apr 03 '13 at 14:57
  • Thanks sheerun, I've changed it from `file.open` to use `Rack::Test::UploadedFile.new` instead. – Ryan May 23 '13 at 23:08