【问题标题】:rspec to test respond_to format and csvrspec 测试 respond_to 格式和 csv
【发布时间】:2017-02-27 04:24:51
【问题描述】:

我想测试我的 rspec 控制器中是否 top_users eq User.top_users。 如何访问 format.csv?我需要类似的东西:

it "format csv" do
  get :index, format: :csv
  # expect(something)……
end

稍后想测试csv:如果文件格式正确,则无需保存/下载。

控制器:

def index
  respond_to do |format|  
    format.csv do
      top_users = User.top_users

      send_data(
        top_users.to_csv,
        filename: "top-users-#{Time.zone.today}.csv"
      )
    end
  end
end

型号:

def self.to_csv
  CSV.generate(headers: true) do |csv|
    csv << [‘one’, ‘two’]

    all.each do |user|
      csv << user.csv_data
    end
  end
end

csv_data 是:[user.name, user.email] 左右……

【问题讨论】:

  • 当您尝试此处向我们展示的示例规范时发生了什么?
  • 好的,这不是完整的错误消息...您能否转到您的日志文件 (log/test.log) 并重新运行规范,然后在其中找到错误并向我们展示更多信息?一点:您是否直接从您的应用程序复制/粘贴了此代码?您是否注意到您问题中的代码具有奇怪的字符串格式?那是因为在您复制/粘贴的代码中使用了奇怪的“特殊”引号。可能是 ruby​​ 解释器发现这些引号很奇怪,例如它期待 ' 并找到 ` 并认为字符串没有正确关闭也 " vs

标签: ruby-on-rails ruby csv ruby-on-rails-4 rspec


【解决方案1】:

CSV、PDF 或其他格式无关紧要,您可以从格式为 csv 的 get 请求中获得响应。 这是我测试我的 csv 生成器的方式:

describe "GET/index generate CSV" do
  before :each do
    get :index, format: :csv
  end

  it "generate CSV" do
    expect(response.header['Content-Type']).to include 'text/csv'
    expect(response.body).to include('what you expect the file to have')
  end
end

就是这样。

对于您拥有的每个用户,您可以执行以下操作:

 User.top_users.each do |user|
   expect(response.body).to include(user.name) # or the attr you want to check if it's in the file
 end

您还可以添加 'pry' gem,将 binding.pry 放在 expect 之前并查看响应以及哪些元素将有助于您检查该方法是否按预期正常工作。

【讨论】:

  • 我复制了你的代码,它给了我 -> 未定义的方法 `request='
  • 请求=?你在我的代码或你的代码中看到任何请求方法吗!
【解决方案2】:

如果遇到错误unknown keyword: :format,试试这个:

describe "GET/index generate CSV" do    
  it "generate CSV" do
    get :index, params: {format: :csv}
    expect(response.header['Content-Type']).to include 'text/csv'
    expect(response.body).to include('what you expect the file to have')
  end
end

【讨论】:

    猜你喜欢
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-05
    • 1970-01-01
    • 1970-01-01
    • 2016-10-15
    • 2015-06-01
    相关资源
    最近更新 更多