RSpec 要求用户输入
RSpec asking for user input
我有两个问题。给定下面的 ruby 代码,你会在 RSpec 中编写什么样的测试,当 运行 测试时你会如何避免被要求输入用户输入?我尝试了很多方法,例如:
- 允许($stdout)
- 允许(内核)
- 存根(:获取)
- STDOUT.should_receive(:puts).with("exit")
- 允许($stdin).接收(:gets).and_return('no_gets')
- allow_any_instance_of(内核).接收(:gets).and_return('exit')
但以上方法均无效。在测试中不断询问我的用户输入。
class EchoApp
def greeting
while(true)
puts "Say something:"
user = gets.chomp
break if user == 'exit'
end
return "Goodbye!"
end
end
您的建议应该确实有效。但还有另一种选择。
orig_stdin = $stdin
$stdin = StringIO.new('exit')
assert(EchoApp.new.greeting,'Goodbye!')
# Or
expect(EchoApp.new.greeting).to eql('Goodbye!')
$stdin = orig_stdin
如果这不起作用,请告诉我。
我有两个问题。给定下面的 ruby 代码,你会在 RSpec 中编写什么样的测试,当 运行 测试时你会如何避免被要求输入用户输入?我尝试了很多方法,例如:
- 允许($stdout)
- 允许(内核)
- 存根(:获取)
- STDOUT.should_receive(:puts).with("exit")
- 允许($stdin).接收(:gets).and_return('no_gets')
- allow_any_instance_of(内核).接收(:gets).and_return('exit')
但以上方法均无效。在测试中不断询问我的用户输入。
class EchoApp
def greeting
while(true)
puts "Say something:"
user = gets.chomp
break if user == 'exit'
end
return "Goodbye!"
end
end
您的建议应该确实有效。但还有另一种选择。
orig_stdin = $stdin
$stdin = StringIO.new('exit')
assert(EchoApp.new.greeting,'Goodbye!')
# Or
expect(EchoApp.new.greeting).to eql('Goodbye!')
$stdin = orig_stdin
如果这不起作用,请告诉我。