RSPEC - 测试类方法to_csv



我的模型中有这个类方法:

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

我正在寻找使用 Rspec 测试此方法的好方法。有没有人对这种方法有很好的技术?

我有几点意见:

  • 我不会使用all除非您在后台工作,或者您知道集合不会那么大
  • 如果你真的必须使用all,那么不要使用.each使用.find_each它会批量执行查询
  • 如果可以,请使用工厂机器人

对于规范本身,我会做:

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 "titlentitle1ntitle2n"
end

最新更新