Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test CSV download in capybara and poltergeist?

I need to be able to test the contents of a CSV file that my Rails application is returning.

In my controller, the code looks like:

respond_to do |format|
  format.html
  format.js
  format.csv do
    if current_user.has_rights?
      response.headers['Content-Type'] = 'text/csv'
      response.headers['Content-Disposition'] = 'attachment; filename=info.csv'    
      send_data generate_csv_file
    else
      send_data "Access denied"
    end
  end
end

And this code works-- if I visit that URL with the appropriate rights, then the CSV file is downloaded. However, I can't seem to get any kind of appropriate test working with Poltergeist and Capybara.

If I do the following, following the response to this question:

describe DashboardsController do
  context "when format is csv" do
    render_views
    let(:csv_string)  { get_csv_headers }
    let(:csv_options) { {filename: "report.csv", disposition: 'attachment', type: 'text/csv; charset=utf-8; header=present'} }
    let (:csv_user) {FactoryGirl.create(:csv_user)}
    before do
      sign_in csv_user
    end


    it "should return a csv attachment" do
#      @controller.should_receive(:send_data).with("#{csv_string.join(',')}", csv_options).
#        and_return { @controller.render nothing: true } # to prevent a 'missing template' error
      get :index, format: :csv
      puts response.headers
      puts response.body
    end
  end
end

The header that's reported via that puts:

{"Location"=>"http://test.host/", "Content-Type"=>"text/html; charset=utf-8"}
<html><body>You are being <a href="http://test.host/">redirected</a>.</body></html>

which is clearly wrong. What can I do to get the response for a csv format be csv within the context of the test? (please note that I've already included render_views, as suggested in this question).

like image 266
mmr Avatar asked Oct 21 '22 15:10

mmr


1 Answers

I'm suffering through the same issue right now. This might help you. => http://sponsorpay.github.io/blog/2012/11/29/capybara-poltergeist-and-csv-downloads/

This may also be relevant. => Downloading file to specific folder using Capybara and Poltergeist driver

like image 110
Lawson Kurtz Avatar answered Nov 15 '22 06:11

Lawson Kurtz