views:

175

answers:

4

I have model Person that has many Images, where images has a Paperclip attachment field called data, an abbreviated version displayed below:

class Person
  has_many :images
  ...
end

class Image
  has_attached_file :data
  belongs_to :person
  ...
end

Person is required to have at least one Image attached to it.

When using FactoryGirl, I have code akin to the following:

Factory.define :image do |a|
  a.data { File.new(File.join(Rails.root, 'features', 'support', 'file.png')) }
  a.association :person
end

Factory.define :person do |p|
  p.first_name 'Keyzer'
  p.last_name 'Soze'
  p.after_create do |person|
    person.assets = [Factory.build(:image, :person => person)]
  end
  # p.images {|images| [images.association(:image)]}
end

(N.B. I have also tried the code commented out above was also tried) Most of the time when I run cucumber features, I get an error akin to the following:

No such file or directory - /tmp/stream,9887,0.png (Errno::ENOENT)

...

Sometimes the tests run successfully.

Can anyone tell me what the problem is I am having here or how they use FactoryGirl and Paperclip together to achieve something like what I am trying to achieve?

I am using Rails 3.

+1  A: 

Try using ActionController::TestUploadedFile. You can just set the file property to an instance of TestUploadedFile and paperclip should take care of the rest. For example

valid_file = File.new(File.join(Rails.root, 'features', 'support', 'file.png'))  
p.images { 
   [
     ActionController::TestUploadedFile.new(valid_file, Mime::Type.new('application/png'))
   ] 
}
britt
A: 

What are you testing exactly? That paperclip will successfully attach the file? That really seems like a test that paperclip should handle, not your application.

Have you tried

a.data { File.join(Rails.root, 'features', 'support', 'file.png') }

We use Machinist instead of factory_girl and have just used things like

Image.blueprint do
  image { RAILS_ROOT + 'spec/fixtures/images/001.jpg' }
end

Though, we aren't really testing much when we do this, we typically just want to have a valid Image object.

theIV
+1  A: 

I've been using the code in the gist below:

http://gist.github.com/162881

deb
A: 

file { File.new(Rails.root.join('spec', 'fixtures', 'filename.png')) }

Matthew Deiters