Rails + Rspec:如何测试rake任务“put”/“print”?

时间:2013-06-10 19:00:48

标签: ruby-on-rails rspec

我有一个rake任务,只是循环遍历我的所有产品,并在产品保存时增加一个计数器。然后打印出那个计数器。如何测试puts的编号?

task(:resave_every_product => :environment) do
    total_products = 0
    counter = 0
    all_products = Product.find(:all)
    puts "done loading all products"
    puts "starting resaving..."
        all_products.each do |product|

            puts "current product is #{product.id}" if (counter%1000 == 0)
            counter += 1 if product.save
        end

    puts "done resaving products."
    puts "total products - #{all_products.size}"
    puts "products resaved - #{counter}"
end

1 个答案:

答案 0 :(得分:2)

如果您愿意使用puts转换为Logger(除非您有特定的理由使用puts,这是明智的),您可以在RSpec中测试输出,如下所示:

 Rails.logger.should_receive(:info).with('done loading all products')