rubyunit-testingcsvtestunit

Stub a CSV file in Ruby Test::Unit


So I have a Ruby script which parses a CSV file as a list of rules and does some processing and returns an array of hashes as processed data.

CSV looks like this:

id_number,rule,notes
1,"dummy_rule","necessary"
2,"sample_rule","optional"

The parsing of CSV looks like this:

def parse_csv(file_name)
  filtered_data = []
  CSV.foreach(file_name, headers: true) do |row|
    filtered_data << row # some processing
  end
  filtered_data
end

Now I am wondering if it is possible to stub/mock an actual CSV file for unit testing in such a way that I could pass a "filename" into this function. I could make a CSV object and use the generate function but then the actual filename would not be possible.

def test_parse_csv
   expected_result = ["id_number"=>1, "rule"=>"dummy_rule", "notes"=>"optional"}]
   # stub/mock csv with filename: say "rules.csv"
   assert.equal(expected_result, parse_csv(file_name))
end

I use Test::Ruby

I also found a ruby gem library called mocha but I don't know how this works for CSVs

https://github.com/freerange/mocha

Any thoughts are welcome!


Solution

  • I would create a support directory inside your test directory then create a file..

    # test/support/rules.csv
    id_number,rule,notes
    1,"dummy_rule","necessary"
    2,"sample_rule","optional"
    

    Your test should look like this, also adding an opening curly bracket which looks like you've missed on line #2.

    def test_parse_csv
       expected_result = [{"id_number"=>1, "rule"=>"dummy_rule", "notes"=>"optional"}]
       assert.equal(expected_result, parse_csv(File.read(csv_file)).first)
    end
    
    def csv_file
      Rails.root.join('test', 'support', 'rules.csv') 
    end
    

    EDIT: Sorry, I should have noticed this wasn't Ruby on Rails... heres a ruby solution:

    def test_parse_csv
       expected_result = [{"id_number"=>1, "rule"=>"dummy_rule", "notes"=>"optional"}]
       assert.equal(expected_result, parse_csv(csv_file).first)
    end
    
    def csv_file
      File.read('test/support/rules.csv') 
    end