As low-tech as CSV is, it doesn't appear to be going away anytime soon. So, I've run into a few different Ruby on Rails projects that want import from/export to CSV capability, and because I like tests, I wanted to make sure I could test not only that the CSV is exported but that the content of the CSV is correct.
Here's how to do this using Capybara and Rspec:
First, switch the driver to something that works (webkit or rack_test, but not selenium). To do this, you can run this within your code block:
Capybara.javascript_driver = :webkit
Just make sure to change it back to your preferred driver after you're done. Another option is to do this in your
spec_helper.rb
:
config.before(:each, webkit: true) do
Capybara.javascript_driver = :webkit
end
config.after(:each, webkit: true) do
Capybara.javascript_driver = :selenium
# or whatever your preferred driver is
end
Then just tag any CSV tests with the
webkit: true
tag.
(Thanks to
Kevin Bedell on StackOverflow for this one.)
Once you get the driver configured properly, you can check the headers and the actual content of the CSV trivially:
click_on 'Download as CSV'
# Make sure the page is a CSV
header = page.response_headers['Content-Disposition']
expect(header).to match /^attachment/
expect(header).to match /filename="my_file.csv"$/
# Then check the content
MyModel.all.each do |record|
expect(page).to have_content record.field1
expect(page).to have_content record.field2
end
(Props to
Andrew on StackOverflow for this bit.)