Reputation: 6043
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?
Upvotes: 2
Views: 455
Reputation: 198324
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.
Upvotes: 3