5

I'm new to unit testing in Ruby and I'm having some trouble creating a spec that will check for STDOUT. I know how to test STDOUT if the code I'm testing is within a Class/Method, but I want to just test a puts statement coming from a regular Ruby file that's not within a Class or Method.

Here is the simple one liner from my_file.rb

puts "Welcome to the Book Club!"

Here's the spec

my_spec.rb

require_relative 'my_file.rb'

  describe "Something I'm Testing" do
    it 'should print Welcome to the Book Club!' do

        expect {$stdout}.to output("Welcome to the Book Club!\n").to_stdout

      end
    end

I get the following error message:

Failures:

  1) Something I'm Testing should print Welcome to the Book Club!
     Failure/Error: expect {$stdout}.to output("Welcome to the Book Club!\n").to_stdout

       expected block to output "Welcome to the Book Club!\n" to stdout, but output nothing
       Diff:
       @@ -1,2 +1 @@
       -Welcome to the Book Club!
       # ./spec/my_spec.rb:9:in `block (2 levels) in <top (required)>'

Finished in 0.01663 seconds (files took 0.08195 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/my_spec.rb:7 # Something I'm Testing should print Welcome to the Book Club!

I thought I can just use $stdout to capture the STDOUT from my_file.rb but that didn't work. The output keeps saying its nothing. I found this post that speaks about capturing output via StringIO Testing STDOUT output in Rspec

But that method didn't work for me. What am I doing wrong?

Thanks!

Community
  • 1
  • 1
salce
  • 409
  • 1
  • 12
  • 28

1 Answers1

8

Your puts method is called when you included the my_file.rb right at the top, before your tests have run. Include it within your test.

describe "Something I'm Testing" do
  it 'should print Welcome to the Book Club!' do
     expect { require_relative 'my_file.rb' }.to output("Welcome to the Book Club!\n").to_stdout
  end
end
Uzbekjon
  • 11,655
  • 3
  • 37
  • 54
  • Thank you! Worked like a charm. Will keep in mind for next time. – salce May 18 '16 at 21:18
  • 1
    If @Uzbekjon answered your question, please accept his answer by clicking the check icon. See http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work for more information. – Keith Bennett May 19 '16 at 04:34
  • 1
    This solution works, but if you have multiple tests with different stdout output, the output from the first test interfere with the one from the second. – Sebastian Corneliu Vîrlan May 22 '18 at 17:12