Testing File Uploads in Rails Without Fixtures

written in ruby

While working on some functional tests for a controller, I needed to be able to test uploading a file. Fairly standard, but in this case I didn’t want to just use fixture_file_upload as the related objects were being created by Machinist from a blueprint. That’s where Rack::Test comes in. Rack::Test::UploadFile allows you to post a Tempfile given its path and content type. Perfect! No fixtures needed.

So all I had to do was create a Tempfile, write my CSV contents to it, and post using the instance of UploadFile. Here’s a small snippet showing an example:

1
2
3
4
5
6
7
8
9
# Build the csv contents
csv = 'user, field2, field3'

file = Tempfile.new(['file_name', '.csv'])
file.write(csv)
file.rewind

post_as @admin, :upload_file,
  :file => Rack::Test::UploadedFile.new(file.path, 'text/csv')

Comments