简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM