Quantcast
Channel: Blogfreakz - Web Design and Web Development resources » Upload
Viewing all articles
Browse latest Browse all 10

Testing CSV File Uploads In Ruby

$
0
0

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,name1@example.com
Name2,name2@example.com
Name3,name3@example.com
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:


Viewing all articles
Browse latest Browse all 10

Latest Images

Trending Articles





Latest Images