File upload with Fabrication Gem

I ran into some problems when testing controller code with rspec and fixtures created by fabrication. Some tests failed because the file object was type casted to a string. So I googled around and found this blogpost how to fix it in your spec. Luckily you can use it in your fabricators, too. See this small example:

Fabricator(:media_item) do
  file { Rack::Test::UploadedFile.new(Rails.root.join('spec','fabricators','test.pdf')) }
  type :pdf
end

There is a shortcut rails method for this, called fixturefileupload, but this didn't work for me in a fabricator.

2012-10-15 Followup

It has shown, that Rack::Test::UploadedFile will not work in exactly the same way as Rails does. So if you are using Rails and want to have the exact behaviour, use this little longer code:

Fabricator(:media_item) do
  file {
    ActionDispatch::Http::UploadedFile.new(
      :tempfile => File.new(Rails.root.join('spec','fabricators','test.pdf')),
      :filename => File.basename(File.new(Rails.root.join('spec','fabricators','test.pdf')))
    )
  }
  type :pdf
end