Testing CSV File Uploads In Ruby

Testing the functionality of a CSV file uploader may seem to be simple and straightforward at first but as it turns out – not quite as explained in Ruby Quicktips.

ScreenHunter 580 Oct. 09 13.28 Testing CSV File Uploads In Ruby

Say if you have a form for uploading CSV files like the one below:

<%= form_tag csv_import_path, :multipart => true do %>
 <%= file_field_tag :file, :accept => "text/csv" %>
 <%= submit_tag "Upload" %>
<% end %>    

And your controller action looks something like this:

require 'csv'
def csv_import    
 file_data = params[:file].read
 csv_rows  = CSV.parse(file_data)
 csv_rows.each do |row|
 # do something with each row
 end
 respond_to do |format|
 format.html { redirect_to your_path, :notice => "Successfully imported the CSV file." }
 end
end   

You can’t just use fixture_file_upload and then create a sample file inside your test/fixtures/files/ for testing as explained here. Instead, you can use the Tempfile and Rack::Test::UploadFile classes and manually create a CSV file and then supply it to the post (or put) method as shown below:

def test_should_successfully_import_csv
 csv_rows = <<-eos
Name1,[email protected]
Name2,[email protected]
Name3,[email protected]
eos
 file = Tempfile.new('new_users.csv')
 file.write(csv_rows)
 file.rewind
 assert_difference "User.count", 3 do
 post :csv_import, :file => Rack::Test::UploadedFile.new(file, 'text/csv')
 end
 assert_redirected_to your_path
 assert_equal "Successfully imported the CSV file.", flash[:notice]
end

Incoming search terms for the article:

Related Posts

How to Create a Clean and Elegant Blog Layout

Adding Expires Headers In Ruby On Rails

Validate Filename Before Uploading Image Using JavaScript

Rails for Zombies: A Fun Way To Learn Ruby On Rails

1 Comment

  1. Esther

    01.10.2013

    Reply

    Pretty! This has been a really wonderful article. Thanks for providing this information.

Leave a Reply









CommentLuv Enabled