2

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
bigpotato
  • 26,262
  • 56
  • 178
  • 334
  • Does this answer your question? [Testing STDOUT output in Rspec](https://stackoverflow.com/questions/16507067/testing-stdout-output-in-rspec) – TonyArra Apr 13 '22 at 17:16

3 Answers3

2

If you're willing to switch from using puts to Logger (which is advisable unless you have a specific reason to use puts), you can test the output in RSpec like this:

 Rails.logger.should_receive(:info).with('done loading all products')
Michael Lawrie
  • 1,534
  • 11
  • 20
0

Here's a better approach that @TonyArra suggested:

it do 
  expect { subject.invoke }.to output('current product is #123').to_stdout 
end

https://relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/output-matcher

David Hempy
  • 5,373
  • 2
  • 40
  • 68
-1
  it do
    allow(STDOUT).to receive(:puts)
    expect(STDOUT).to receive(:puts).with(`current product is #123`)
    subject.invoke
  end
David Hempy
  • 5,373
  • 2
  • 40
  • 68