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, juan@example.com, $10.00
Pedro, pedro@example.com, $20.00
#...
If you are sending the csv, with send_file or send_data in the controller, you can access the csv with page.body.
And you can get the CSV as an array, by parsing the page.body like this…
CSV.parse(page.body)
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", "juan@example.com", "pedro@example.com"],
["Amount", "$10.00", "$20.00"]
]
And to do this, you can call the transpose method…
CSV.parse(page.body).transpose
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", "juan@example.com", "pedro@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 =)
Here I try 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 posts.