Skip to content

How to: Use test factories

Moxley Stratton edited this page Sep 7, 2017 · 12 revisions

Whereas other gems such as Paperclip allow you to sham mounted uploaders as Strings, CarrierWave requires actual files.

Machinist

Here is an example blueprints.rb file:

User.blueprint do
  avatar { File.open("#{Rails.root}/test/fixtures/files/rails.png") }
end

EDIT:
I believe StringIO's also work.

FactoryGirl

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/jpeg') }
  end
end

As 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
end

Fabrication

Attaching 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
end

You 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
Clone this wiki locally