Benito Serna Tips and tools for Ruby on Rails developers

A simple way of testing a CSV download with capybara

April 20, 2021

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.

CSV example

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
#...

Reading the csv

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)

How to represent the csv data?

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

A test example

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 =)

Related articles

Subscribe to get future posts via email

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.