How do I test if the response of a controller action in Rails is a file? (rack-test or capybara)

Should I use unit tests to do it?

The scenario is simple: I have to test if the exported users from the database are the same contained in the generated .csv from an action.

有帮助吗?

解决方案

You don't need rack-test or Capybara to do this. The default test infrastructure is all you need. Simply check that the Content-Type is CSV:

test "returns a CSV file" do
  get :index, format: :csv
  assert_response :success
  assert_equal "text/csv", response.content_type
end

If you want to take it one step further, you can parse the returned CSV to make sure it is valid and test the values returned:

test "returns a valid CSV file and data" do
  get :index, format: :csv
  assert_response :success
  assert_equal "text/csv", response.content_type

  csv = CSV.parse response.body # Let raise if invalid CSV
  assert csv
  assert_equal 6, csv.size
  assert_equal "Joe Smith", csv[3][4]
end
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top