Capturing STDOUT in RSpec
<p>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 <code>puts</code> statement coming from a regular Ruby file that's not within a Class or Method. </p>

<p>Here is the simple one liner from <code>my_file.rb</code></p>

<pre><code>puts "Welcome to the Book Club!"
</code></pre>

<p>Here's the spec</p>

<p><code>my_spec.rb</code></p>

<pre><code>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
</code></pre>

<p>I get the following error message:</p>

<pre><code>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 &lt;top (required)&gt;'

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!
</code></pre>

<p>I thought I can just use <code>$stdout</code> to capture the STDOUT from <code>my_file.rb</code> but that didn't work. The output keeps saying its nothing. I found this post that speaks about capturing output via <code>StringIO</code> <a href="https://stackoverflow.com/questions/16507067/testing-stdout-output-in-rspec">Testing STDOUT output in Rspec</a></p>

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

<p>Thanks!</p>