2

I'm writing a unit test for my class which reads inputs from stdin. In the unit tests, I'm hoping I can redirect the stdin stream to a string.

How can I achieve this?

0

1 Answer 1

3

To answer your literal question: unlike the constant STDIN, $stdin is just a global variable, you can replace it with another IO object:

require 'stringio'
$stdin = StringIO.new("foo\nbar")
2.times { puts gets }
# => foo
# => bar

But it is probably a better idea to use a proper mocking framework instead, for example like this.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.