Search code examples
rubycsvminitesttestunit

How to assert a CSV file in Ruby


Is there a nice way to assert the contents of a CSV file in Ruby?

I understand how to use the CSV libraries and how to read in the CSV file, but that results in a long list of assertions such as:

`assert_equal("0", @csv_array[0].field('impressions'))
 assert_equal("7", @csv_array[0].field('clicks'))
 assert_equal("330", @csv_array[0].field('currency.GBP.commissions'))
 assert_equal("6", @csv_array[0].field('currency.GBP.conversions'))
 assert_equal("3300", @csv_array[0].field('currency.GBP.ordervalue'))`

Is there some sort of file comparator so I could write:

assert_equal(expected.csv ,actual.csv )

or something along those lines?


Solution

  • How about this:

    expected_csv = "impressions,clicks,currency.GBP.comiisions,currency.GBP.conversions,currency.GBP.ordervalue
    0,7,330,6,3300"
    actual_csv = File.open('actual.csv').read
    assert_equal(expected_csv, actual_csv)
    

    That should work if the entire contents of the CSV file is only 2 lines. Otherwise you will have to manipulate actual_csv to get the parts you want to test. You could do that like so:

    IO.readlines('actual.csv')[3]
    

    That will get you the third line. You can then concatenate with a header line or compare to a string without the header.