Assuming you have a controller action that looks something like this:
require 'csv' # assuming you have this line somewhere
def download
@records = MyModel.all
csv_data = CSV.generate do |data|
data << ["Field 1", "Field 2"]
@records.each do |record|
data << [record.field1, record.field2]
end
end
send_data csv_data, type: "text/csv", filename: "my_file.csv"
end
I was able to use Capybara to verify that clicking my button would have caused the browser to trigger a download prompt:
click_on 'Download as CSV'
header = page.response_headers['Content-Disposition']
header.should match /^attachment/
header.should match /filename="my_file.csv"$/
Note that page.response_headers
is driver specific. I'm using capybara-webkit. A Content-Disposition
header should contain attachment
rather than inline
for it to cause a download prompt. Capybara also displayed the content of the file as the response body (although this may also be driver specific), so it was easy to verify the output:
MyModel.all.each do |record|
page.should have_content record.field1
page.should have_content record.field2
end
get :show, id: 42, format: :csv
, theresponse.body
will contain the CSV content.