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?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
His
  • 5,891
  • 15
  • 61
  • 82

1 Answers1

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.

Community
  • 1
  • 1
Amadan
  • 191,408
  • 23
  • 240
  • 301