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
joomla 1.5 templates
01.09.2013
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!
There are no trackbacks to display at this time.