cialis online pharmacy generic xenical cheap cialis online cialis generic viagra online in canada buy cheap levitra online cialis without a perscription order viagra uk no prescription flagyl cheap generic levitra buying viagra in the uk cheap viagra approved cialis deltasone online buy viagra online without prescription non prescription cialis buy orlistat uk buy cialis in india prednisone 60 mg female viagra online buy viagra without prescription celebrex prescriptions buy cialis canada best prices viagra alternative to prednisone cheapest generic levitra levitra 5mg cheap viagra cialis on line buy xenical without prescription online accutane canadian health care prednisone no prescreption viagra online generic female viagra europe buy cialis low price cheap india viagra

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.

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

Related Posts

Adding Instagram Badges to Your WordPress Profile

How to Create a Custom WordPress Registration Form with Flat UI

How to Create A Basic Hipster-Style Layout

How to Style Nav Links Using Floats With HTML5 and CSS3

1 Comment

  1. It’s a shame you don’t have a donate button! I’d without a doubt donate to this superb blog! I guess for now i’ll settle for bookmarking and adding your RSS feed to my
    Google account. I look forward to new updates and will
    talk about this website with my Facebook group.
    Talk soon!