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,[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
1 Comment
Esther
01.10.2013
Pretty! This has been a really wonderful article. Thanks for providing this information.
There are no trackbacks to display at this time.