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!
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With