Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing CSV.generate with RSpec

I have the following helper in a rails 3.1 project - I'm just wondering if there's a way to test that CSV.generate call. I'd love to say I have some sort of idea how to do it, but the truth is I don't even know where to start. Any ideas appreciated.

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
like image 659
PlankTon Avatar asked Nov 04 '11 19:11

PlankTon


1 Answers

I would write it so:

# 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
like image 77
Sławosz Avatar answered Nov 08 '22 04:11

Sławosz