【问题标题】:Test contents of file in rspec from respond_to format.csv从respond_to format.csv测试rspec文件的内容
【发布时间】:2013-05-20 10:33:17
【问题描述】:

我的控制器中有以下用于导出 csv 文件的代码

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

我的规范中有以下内容

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 在我检查时在此测试中为空。当在浏览器中点击此操作时,我将如何获取下载的规范中的 csv 文件,以便我可以检查结果?我在试图弄清楚这一点时遇到了一些困难。

感谢您提供的任何帮助。

【问题讨论】:

    标签: ruby-on-rails-3 rspec rspec-rails respond-to


    【解决方案1】:

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

    it 'should create a CSV file ' do
        get csv_create_path
        response.header['Content-Type'].should include 'text/csv'
    end
    

    【讨论】:

      【解决方案2】:

      您有点指定支持 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 视图设置了适当的实例变量。

      【讨论】:

        猜你喜欢
        • 2017-02-27
        • 1970-01-01
        • 1970-01-01
        • 2016-10-20
        • 1970-01-01
        • 1970-01-01
        • 2015-03-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多