Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
Jul 22 ’12

Testing CSV file uploads

Let’s say you have a form like this for uploading a CSV file:

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

And your controller action looks 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

How would you test this functionality?

You can’t use fixture_file_upload and stick a sample file in test/fixtures/files/ (as often suggested - e.g. here on SO). That’s because CSV and YAML files will be imported as fixtures into the test database as soon as you run tests. E.g., this would not work:

def test_file_upload
  post :csv_import, :file => fixture_file_upload('files/new_users.csv','text/csv')
end

But what you can do is to use the Tempfile and Rack::Test::UploadFile classes and manually create a CSV file and supply this to the post (or put) method:

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

11 notes 0 comments

  1. Imagedeepcleaningcorona reblogged this from rubyquicktips
  2. Imagetexasworkshop said: texasminiatureshowcase….
  3. Imagetakkanm reblogged this from rubyquicktips
  4. Imagerubyquicktips posted this

Comments

You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus