簡體   English   中英

使用RSpec測試CSV.generate

[英]Testing CSV.generate with RSpec

我在rails 3.1項目中有以下幫助器 - 我只是想知道是否有辦法測試CSV.generate調用。 我想說我有一些想法怎么做,但事實是我甚至不知道從哪里開始。 任何想法都贊賞。

require 'csv'

module Admin::PurchasesHelper
  def csv_purchase_list
    columns = ['course', 'amount', 'first_name', 'last_name', 'contact_phone', 'contact_mobile', 'created_at']
    CSV.generate(:col_sep => ";", :row_sep => "\r\n", :headers => true, :write_headers => true, :return_headers => true) do |csv|
      csv << ["Course", "Amount", "First Name", "Last Name", "Phone", "Mobile", "Created At"]
      Purchase.all.each do |p|
        csv << columns.collect{ |name| p.send(name)}
      end
    end
  end
end

我會這樣寫的:

# helper class to get access to csv_purchase_list
class Foo
  include Admin::PurchasesHelper
end

it "should return Purchases as csv" do
  # create some objects - you have to know its values
  Factory(:purchase)
  Factory(:purchase)

  # you have to prepare file.csv with content from objects created above
  expected_csv = File.read('file.csv')
  generated_csv = Foo.new.csv_purchase_list

  # sometimes it is better to parse generated_csv (ie. when you testing other formats like json or xml
  generated_csv.should == expected_csv
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM