Do you need/want to test a CSV download with capybara, but don’t know how to do it?
Here I will show you a simple way of doing it if you are using the default driver.
Imagine that in your feature you are exporting a csv like this one…
User, Email, Amount Juan, firstname.lastname@example.org, $10.00 Pedro, email@example.com, $20.00 #...
If you are sending the csv, with
send_data in the controller, you can access the csv with
And you can get the
CSV as an array, by parsing the
page.body like this…
One way to represent the data in a readable way for your tests is to “transpose” the csv data to show the columns as rows, like this…
[ ["User", "Juan", "Pedro"], ["Email", "firstname.lastname@example.org", "email@example.com"], ["Amount", "$10.00", "$20.00"] ]
And to do this, you can call the
Putting it all together, a test could look like this…
RSpec.feature "My feature" do scenario do visit page_with_csv_button_path click_on "Download csv" expect(csv).to eq([ ["User", "Juan", "Pedro"], ["Email", "firstname.lastname@example.org", "email@example.com"], ["Amount", "$10.00", "$20.00"] ]) end def csv CSV.parse(page.body).transpose end end
And that’s all!… I hope it helps =)
I send an email each week, trying to share knowledge and fixes to common problems and struggles for ruby on rails developers, like How to fetch the latest-N-of-each record or How to test that an specific mail was sent or a Capybara cheatsheet. You can see more examples on Most recent posts or All post by topic.