5

I have the following code in my controller that exports a csv file

...
  def export
    @filename = 'users.csv'
    @output_encoding = 'UTF-8'
    @users = User.active_users #not the actual scope but this only returns active
    respond_to do |format|
      format.csv
    end
  end
...

And I have the following in my spec

it "should only return active users"
  get :export, :format => :csv
  # i want to check that my mocked users_controller#export is only returning the active users and not the inactive ones  
end

response.body is empty in this test when i check it. How would I go about getting the csv file in the spec that is downloaded when this action is hit in a browser so that i can check the result? I've hit a bit of a wall trying to figure this out.

Thanks for any help you can provide.

kwbock
  • 647
  • 5
  • 13

2 Answers2

0

A test that checks that a CSV file is being created is as follows, assuming that the controller action is at 'csv_create_path'

it 'should create a CSV file ' do
    get csv_create_path
    response.header['Content-Type'].should include 'text/csv'
end
Obromios
  • 15,408
  • 15
  • 72
  • 127
-1

You sort of specify that CSV format is supported, but not what the contents should be. You could do

respond_to do |format|
  format.csv do
    render text: File.read(@filename)
  end
end

to actually render that CSV file.

If you also have a normal HTML formatted view for the same data, you would simply have

respond_to do |format|
  format.html
  format.csv do
    render text: File.read(@filename)
  end
end

assuming you have setup appropriate instance variables for the HTML view before.

EdvardM
  • 2,934
  • 1
  • 21
  • 20