Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

ruby on rails - How Do I Use Factory Girl To Generate A Paperclip Attachment?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use fixture_file_upload

include ActionDispatch::TestProcess in your test helper, here is an example factory:

include ActionDispatch::TestProcess

FactoryBot.define do
  factory :user do
    avatar { fixture_file_upload(Rails.root.join('spec', 'photos', 'test.png'), 'image/png') }
  end
end

In the above example, spec/photos/test.png needs to exist in your application's root directory before running your tests.

Note, that FactoryBot is a new name for FactoryGirl.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...