How I test a file upload in Rails 3
In previous version of Rails I used ActionController::TestUploadedFile.new to test file uploads, but in Rails 3 you have to use Rack::Test::UploadedFile.new
The file object that is created can then be used as a parameter in Rspec, TestUnit or Cucumber
Below a Test example:
test "avatar upload" do
avatar_filename = path-to-fixtures-image + "/avatar.jpg"
file = Rack::Test::UploadedFile.new(avatar_filename, "image/jpeg")
post "/create", :user => { :avatar => file }
... asserts ...
end
And a Cucumber example:
When /^I request to create a stream with "([^"]*)" user id and photo "([^"]*)"$/ do |user_name, photo|
file_path = "#{::Rails.root.to_s}/features/photos/#{photo}"
mime_type = "image/jpeg"
user = User.find_by_name(user_name)
params = { :photo => {:user_id =>user.id,
:data => Rack::Test::UploadedFile.new(file_path, mime_type) } }
visit api_v1_streams_path(:format => 'json'), :post, params
end