Bitwise
Bitwise

Reputation: 8451

RSPEC - Test to_csv class method

I have this class method in my model:

def self.to_csv
  attributes = %w(title)

  CSV.generate(headers: true) do |csv|
    csv << attributes

    all.each do |campaign|
      csv << campaign.attributes.values_at(*attributes)
    end
  end
end

I'm looking for good ways to test this method with Rspec. Does anyone have good techniques for this method?

Upvotes: 0

Views: 226

Answers (1)

apneadiving
apneadiving

Reputation: 115531

I have a few comments:

  • I would not use all unless you are in a background job or you know the collection would not be that big
  • if you really have to use all, then dont use .each use .find_each which would do queries in batches
  • use factory bot if you can

For the spec itself, I would do:

it "creates expected csv" do 
  allow(described_class).to receive(:all).and_return([
    described_class.new(title: "title1"),
    described_class.new(title: "title2")
  ])
  expect(described_class.to_csv).to eq "title\ntitle1\ntitle2\n"
end

Upvotes: 3

Related Questions