简体   繁体   English

Rails + Rspec:如何测试什么耙任务“放置” /“打印”?

[英]Rails + Rspec: How to test what a rake task “puts” / “print”?

I have a rake task that merely loops through all my products and increments a counter if the product saves. 我有一个rake任务,该任务只循环遍历我所有的产品,如果产品保存,则增加一个计数器。 It then prints out that counter. 然后打印出该计数器。 How do I test what number it puts ? 如何测试它什么号码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

如果您愿意从使用puts切换到Logger(除非您有特定的使用理由,否则建议这样做),可以在RSpec中测试输出,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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