Old Guy New Trick

An old guys journey to learn how to code.

Testing to_csv Method


Author: John on September 23, 2014

Last week I covered a topic that resurfaced while I am in the process of upgrading one of our apps from Ruby 1.9 and Rails 3.x. When I wrote that application I was a raw recruit - fresh to Ruby and Rails and just trying to get the idea to work.

But as I've been improving my skills and expanding the ole grey matter, I wanted to write this new version, fully tested.  In the application there is a need to be able to export the data to a CSV formatted file.  I had the code from the old version of the app, and migrated it over.  However, I challenged myself to figure out how to write a test for the to_csv method in Baytech model.

Below is the code from the Baytech model:

def self.to_csv
CSV.generate(col_sep: ':') do |csv|
    all.each do |baytech|
      port = "X"
      csv << [baytech.name, baytech.phone_num, baytech.ip_addr, port, baytech.modem_type, port]
  end
end

I know the method works, as it has been working fine for 9 months or so now.  But I really wanted to figure out how to write a test for this method.  After much trial and error, along with research via books and google, I came up with the following solution:

describe Baytech, '#to_csv' do
let(:baytech) { FactoryGirl.create(:baytech) }

  before do
    baytech
  end

  it { expect(Baytech.to_csv).to match /#{baytech.name}:#{baytech.phone_num}:#{baytech.ip_addr}:X:1:X/ }
end

You may notice in the above code that I am referencing a Factory.  Here is a short version of that factory file:

FactoryGirl.define do
factory :baytech do
    sequence(:name) {|n| "jaxfl0#{n}b9" }
    sequence(:ip_addr) {|n| "10.1.2.#{n}" }
    phone_num "7091234384"
    region "USA"
    modem_type "1"
    ip_method "ssh"
    active true
    has_modem_line true
    updated_by "cd1234"

    {-snip-}

  end
end

The keen eye may have caught something interesting in the to_csv method.  I'm using an option, col_sep: ':' which allows me to use the : character as the delimiter instead of the default comma.

With the test in place, and passing, I felt better about the code in my to_csv method.

Learn Something New Every Day

Last Edited by: John on November 11, 2015