如何在capybara和poltergeist中测试CSV下载?

时间:2014-01-27 18:51:17

标签: ruby-on-rails capybara poltergeist

我需要能够测试我的Rails应用程序返回的CSV文件的内容。

在我的控制器中,代码如下:

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

此代码有效 - 如果我访问具有相应权限的URL,则会下载CSV文件。但是,我似乎无法与Poltergeist和Capybara进行任何合适的测试。

如果我执行以下操作,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

通过以下方式报告的标题:

{"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>

这显然是错误的。在测试环境中,如何才能获得csv格式的响应? (请注意,我已经包含render_viewsas suggested in this question)。

1 个答案:

答案 0 :(得分:3)

我现在正在经历同样的问题。这可能对你有帮助。 =&GT; http://sponsorpay.github.io/blog/2012/11/29/capybara-poltergeist-and-csv-downloads/

这也可能是相关的。 =&GT; Downloading file to specific folder using Capybara and Poltergeist driver