Testing file uploads in Ruby on Rails

In the current version of Ruby on Rails (1.0), testing file uploads is a little involved. It’s possible but involves writing your own code to handle the process. Cue my first Rails patch. In Rails 1.1 you will be able to put spongebob.png in a test/fixtures/files directory, and add the “upload” to the params of your test request:

post :change_avatar, :avatar => fixture_file_upload('/files/spongebob.png', 'image/png')

Posted on Saturday, March 18, 2006.

8 Comments on Testing file uploads in Ruby on Rails

  1. I have a controller: file_upload_controller.rb and an upload action my functional test fails with the following error:

    NoMethodError (undefined method `original_filename’ for #): /app/controllers/file_upload_controller.rb:7:in `upload’

    The only thing I do in the action is to access the original_filename:

    def upload
      file = params[:file]
      print file.original_filename
    end

    Am I doing something wrong?

  2. It looks like something is wrong, but not in the code you’ve shown me. The error indicates the object is a String. In a test file upload, it should be an instance of ActionController::TestUploadedFile*. That would explain why calling file.original_filename causes an error, but doesn’t explain why you get a String in the first place. What code do you have in the functional test?

    • See http://api.rubyonrails.org/classes/ActionController/TestUploadedFile.html
  3. It’s a bug http://dev.rubyonrails.org/ticket/4635

  4. The functional test:

    post 'file/upload', :file => fixture_file_upload('/image.png', 'image/png')
  5. This looks good, but the img_tag form can upload text fields as well as file objects, how would we use ActionController::TestUploadedFile to test a form_tag that doesn’t just upload files..for example I was mucking around with migrations and accidentally blew away my database…what I want to do is create a test that will automatically rebuild my database, uploading files to the FS and populating my database at the same time…any ideas on how to do this??? cheers

  6. I was having the same problem the I noticed that the form I was creating wasn’t didn’t have multipart set to true:

    'create_image'}, :multipart => true) %>

    Hope this helps, -dustin

  7. Dustin – you da man.

    Was having this problem… that ‘multipart’ thing was the trick.

    I just ended up hardcoding it in html:

  8. I finally got a good functional test working for attachment_fu. Below is a snippet:

    http://pastie.caboo.se/66182

    All of the details are in this post:

    http://www.subelsky.com/2007/05/functional-testing-for-attachment-fu.html#links

Post a comment

You may use Textile for formatting.