Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

stdout

rspec

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.

like image 253
user3546952 Avatar asked Dec 02 '25 07:12

user3546952


1 Answers

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.

like image 130
user3546952 Avatar answered Dec 04 '25 00:12

user3546952