-
Notifications
You must be signed in to change notification settings - Fork 1.7k
How to: Use test factories
Liang edited this page Mar 30, 2017
·
12 revisions
Whereas other gems such as Paperclip allow you to sham mounted uploaders as Strings, CarrierWave requires actual files.
Here is an example blueprints.rb file:
User.blueprint do
avatar { File.open("#{Rails.root}/test/fixtures/files/rails.png") }
endEDIT:
I believe StringIO's also work.
Attaching a file to a FactoryGirl object is pretty much identical.
FactoryGirl.define do
factory :brand do
name "My Brand"
description "Foo"
logo { Rack::Test::UploadedFile.new(File.join(Rails.root, 'spec', 'support', 'brands', 'logos', 'logo_image.jpg'), 'image/jpg') }
end
endAs far as I can tell the curly braces are required to make FactoryGirl attach it lazily, i.e. whenever the factory is built.
If you only need it available for persisted factories (made with create), you can simply do:
FactoryGirl.define do
factory :brand do
name "My Brand"
description "Foo"
after :create do |b|
b.update_column(:logo, "foo/bar/baz.png")
end
end
endAttaching a file to a Fabrication object can be done in an after_create block:
Fabricator(:brand) do
name "My Brand"
description "Foo"
file do
# you'll get an error if the file doesn't exist
File.open(File.join(Rails.root, 'spec', 'support', 'logo_image.jpg'))
end
endYou can also attach a file to Fabrication in Rails 3 like so:
Fabricator(:brand) do
name "My Brand"
description "Foo"
file {
ActionDispatch::Http::UploadedFile.new(
:tempfile => File.new(Rails.root.join("spec/fixtures/assets/example.jpg")),
:filename => File.basename(File.new(Rails.root.join("spec/fixtures/assets/example.jpg")))
)
}
end