Skip to content

Instantly share code, notes, and snippets.

@tommi-lew
Last active August 29, 2015 13:57
Show Gist options
  • Save tommi-lew/9852358 to your computer and use it in GitHub Desktop.
Save tommi-lew/9852358 to your computer and use it in GitHub Desktop.
An example of how I test CSV generation
class Person < ActiveRecord::Base
#... some other methods ...
def self.export_as_csv
#... generates a CSV string ...
end
end
#spec
describe Person do
# 1. Doing a array.join(',') to make the spec more readble,
# instead of creating a stirng directly like this: "1,Bob,50"
# 2. This spec becomes more and more unreadable as more columns are added.
describe '.export_as_csv' do
before do
#... some other stuff...
end
it 'should should return a csv' do
csv = ['Id', 'Name', 'Age'].join(',') + "\n" +
[1, 'Bob', 50].join(',') + "\n" +
[2, 'Alice', 51].join(',')
Person.export_as_csv.should == csv
end
end
end
@cupakromer
Copy link

My initial reaction is to say, this should be pulled into a new class or module. It doesn't really feel the responsibility of a database backed model. With that being said, that doesn't help or address the testing issue. Since this is Rails and you already have ActiveSupport loaded, I may suggest something like:

describe Person do

  it "exports the default fields to csv" do
    # I'd really prefer a stub of what gets returned from the DB, but without
    # more details I can't add that.
    expected_csv = <<-CSV.strip_heredoc
      Id,Name,Age
      1,Bob,50
      2,Alice,51
    CSV
    expect(Person.export_as_csv).to eq expected_csv
  end

end

See the ActiveSupport monkey patch: String#strip_heredoc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment