5

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).

Community
  • 1
  • 1
mmr
  • 14,781
  • 29
  • 95
  • 145

1 Answers1

3

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

Community
  • 1
  • 1
Lawson Kurtz
  • 636
  • 3
  • 6
  • 3
    An answer on this website should include substance, not just links (which are prone to becoming invalid). If you want to provide just links you should do so in a comment on the question. – user664833 Oct 04 '15 at 13:43
  • 1
    and the reason being... that the link becomes invalid (like it is now) so people like me who come looking for the same solution can't get a solution anymore :( – Taryn East Jun 27 '16 at 06:15
  • 1
    First link is available on the Wayback Machine. Before it went down entirely, it redirected to a page mirrored here: http://web.archive.org/web/20141004140513/http://it.fyber.com:80/blog/2012/11/29/capybara-poltergeist-and-csv-downloads – rep Apr 12 '18 at 16:02