Extracting the relevant code snippets from my project to a small standalone test module for clarity ...
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}"
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.
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.
OK. Simple error in the end.
Firstly, inserting a
$buffer.write
line means I am actually writing to the buffer so it's not empty!
Secondly,
@output.puts("string")
doesn't actually assign the string contents to @output ,just uses it as an output channel so
$buffer.write(@output)
just writes hex characters not my string to the buffer.
So I have to explicitly write the string or assign it to the variable i.e.
@output="string"
$buffer.write(@output)
to write the string to the buffer.
Thanks for all the responses which set me researching/thinking in the right way - onwards and upwards.
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