Skip to content

How to: Use test factories

Paweł Gościcki edited this page Jul 31, 2019 · 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.

FactoryBot

Attaching a file to a FactoryBot object is pretty much identical.

FactoryBot.define do
  factory :brand do
    name { "My Brand" }
    description { "Foo" }
    logo { Rack::Test::UploadedFile.new(Rails.root.join('spec/support/logo_image.jpg'), 'image/jpeg') }
  end
end

If you only need it available for persisted factories (made with create), you can simply do:

FactoryBot.define do
  factory :brand do
    name { "My Brand" }
    description { "Foo" }
   
   after :create do |brand|
      brand.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
    Rails.root.join('spec/support/logo_image.jpg').open
  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