Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing STDOUT in RSpec

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!

like image 210
salce Avatar asked Mar 13 '23 06:03

salce


1 Answers

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
like image 110
Uzbekjon Avatar answered Mar 20 '23 16:03

Uzbekjon