【问题标题】:What is the best way to test export to excel or csv using rspec?使用 rspec 测试导出到 excel 或 csv 的最佳方法是什么?
【发布时间】:2011-01-06 16:52:47
【问题描述】:

我正在使用 ruby​​ CSV 库从 Ruby On Rails 应用程序中导出报告数据。 我想知道测试这种操作的最佳方法是什么?

提前致谢

【问题讨论】:

  • Alexey,最好在您的应用中包含示例代码来解释您如何导出 CSV。如果您在内存中准备 CSV 然后进行渲染,则测试将与使用视图输出 CSV 不同。

标签: ruby-on-rails testing csv tdd rspec


【解决方案1】:

您好,我使用的是具有更快 CSV 的 Ruby 1.9.2,但概念应该相似。我实际上有我的工厂在一个辅助方法中,但是把它们放在一起以便在这里更容易看到。我也很想知道是否有更好的方法,但这对我有用。

我生成了报告,然后将其打开以与我的预期结果进行比较。我想确保该文件存在。您可以在不实际保存文件的情况下执行类似操作。

describe "Rsvp Class" do
created = "#{Time.now.to_formatted_s(:db)} -0800"
before(:each) do
  [{:first_name => "fred", :last_name => "flintstone", :state => "CA", :zip => "12345", :created_at => created}, 
    {:first_name => "barny", :last_name => "rubble", :state => "CA", :zip => "12345", :created_at => created}].each do |person|
    rsvp = Factory.build(:rsvp)
    rsvp.first_name = person[:first_name]
    rsvp.last_name = person[:last_name]
    rsvp.state = person[:state]
    rsvp.zip = person[:zip]
    rsvp.created_at = person[:created_at]
    rsvp.save
  end
end
it "should generate a report  csv file" do
  response = "first name, last name, email, address, address line 1, city, state, zip, variation code, tracking code, created at\nfred, flintstone, fred@example.com, , , , CA, 12345, , , #{created}\nbarny, rubble, fred@example.com, , , , CA, 12345, , , #{created}\n"
  Rsvp.generate_report

  string  = ""
  CSV.foreach("#{::Rails.root.to_s}/reports/rsvp_report.csv", :quote_char => '"', :col_sep =>',', :row_sep =>:auto) do |row|
    string << "#{row.join(", ")}\n"
  end
  string.should == response
end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多