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.

4

2 回答 2

0

检查是否正在创建 CSV 文件的测试如下,假设控制器操作位于“csv_create_path”

it 'should create a CSV file ' do
    get csv_create_path
    response.header['Content-Type'].should include 'text/csv'
end
于 2015-10-31T04:33:30.510 回答
-1

您有点指定支持 CSV 格式,但没有指定内容应该是什么。你可以做

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

实际呈现该 CSV 文件。

如果您也有相同数据的普通 HTML 格式视图,您只需

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

假设您之前已经为 HTML 视图设置了适当的实例变量。

于 2013-10-09T14:12:35.927 回答