Skip to content

How to: Use test fixtures

sheerun edited this page Apr 3, 2013 · 7 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:

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

EDIT:
I belive StringIO's also work

FactoryGirl

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

Factory.define :brand do |f|
  f.name "My Brand"
  f.description "Foo"
  f.logo { Rack::Test::UploadedFile.new(File.join(Rails.root, 'spec', 'support', 'brands', 'logos', 'logo_image.jpg')) }
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.

Fabrication

Attaching a file to a Fabrication object can be done in an after_create block:

Fabricator(:brand) do
  name "My Brand"
  description "Foo"
  after_create { |brand| brand.file = File.open(File.join(Rails.root,'spec','support','brands','logos','logo_image.jpg')) } # has to exist
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