Testing STDIN in Ruby

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-28 11:05:08

You can simply stub STDIN:

it "takes user's name and returns it" do
  output = capture_standard_output { game.ask_for_name }
  expect(output).to eq "What shall I call you today?"
  allow(STDIN).to receive(:gets) { 'joe' }
  expect(game.ask_for_name).to eq 'Joe'
end

Actually, you can do the same with STDOUT, without needing to change $stdout:

it "takes user's name and returns it" do
  expect(STDOUT).to receive(:puts).with("What shall I call you today?")
  allow(STDIN).to receive(:gets) { 'joe' }
  expect(game.ask_for_name).to eq 'Joe'
end

Well I can't really be sure, but one problem I had (still have) when working with $stdin / $stdout / StringIO is making sure to run #rewind on them. Are you doing that?

input = StringIO.new
input.puts "joe"
input.rewind
input.gets #=> "joe\n"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!