title: In ruby, how can I capture stdout using a puts and an instance variable. I need to use the instance variable to pass an rspec test
body: <p>Extracting the relevant code snippets from my project to a small standalone test module for clarity ...</p>
  
  <pre><code>require "stringio"  
  
  @output = $stdout
  $buffer = StringIO.new
  $stdout = $buffer
  
  @output.puts "puts method to buffer text" 
  $stdout = STDOUT 
  
  $buffer.rewind 
  puts "buffer contents: #{$buffer.read}"
  </code></pre>
  
  <p>Running this code, returns an empty buffer. I have to use the @output.puts to pass an rspec @output(:puts) should_receive rspec test. If I replace the @output.puts with a simple "puts", the buffer is populated but the rspec test fails.</p>
  
  <p>I have searched various online ruby resources for a couple of hours now and cannot use any of the content to answer this question. Any help gratefully received.</p>