简体   繁体   中英

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. It then prints out that counter. How do I test what number it 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')

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