redirecting stdout to a String

M

Mark Volkmann

I wrote a unit test for a method that writes to stdout. I got it to
work, but I'm not sure my approach was the best. Is there a more
recommended way to do this?

# Create a String with a singleton write method
# that allows it to take the place of stdout.
actual =3D '''
def actual.write(data); self << data; end
old_stdout, $stdout =3D $stdout, actual

# Invoke method to test that writes to stdout.

$stdout =3D old_stdout # restore stdout
 
J

James Edward Gray II

I wrote a unit test for a method that writes to stdout. I got it to
work, but I'm not sure my approach was the best. Is there a more
recommended way to do this?

# Create a String with a singleton write method
# that allows it to take the place of stdout.
actual = '''
def actual.write(data); self << data; end

See the standard library, StringIO.

James Edward Gray II
 
M

Mark Volkmann

See the standard library, StringIO.

Thanks! I have that working, but it's not clear to me how that is
better. In fact, it seems to take more code to do it that way. I now
have this.

require 'stringio'

sio =3D StringIO.new
old_stdout, $stdout =3D $stdout, sio
# Invoke method to test that writes to stdout.
$stdout =3D old_stdout # restore stdout
actual =3D sio.string

Am I overcomplicating this?
 
J

James Edward Gray II

Thanks! I have that working, but it's not clear to me how that is
better. In fact, it seems to take more code to do it that way.

You originally asked:

I was just trying to answer that question.

I prefer the StringIO method because it is a full mock API, as Robert
Dober said. However, if you know you will only need the one method
(now and forever?!) there is probably little difference.

James Edward Gray II
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top