我可以使用 RSpec 来模拟 stdin/stdout 来测试控制台读取吗?写? [英] Can I use RSpec to mock stdin/stdout to test console reads & writes?
问题描述
我的 Ruby 程序从 stdin
读取行并使用 puts
打印到 stdout
(终端).我可以使用 RSpec 来测试读写吗?我可以像在 stdin
中编写的那样向我的程序注入一个字符串,同时检查输出吗?
My Ruby program reads lines from stdin
and uses puts
to print to stdout
(the terminal). Can I use RSpec to test the reads and writes? Can I inject a string to my program like it was written in stdin
and at the same time check the output?
line = STDIN.read.chomp.split
此外,我在循环中进行读取和写入,直到 line[0]
是退出".我可以在循环运行时测试还是应该调用 subject.read_in
和 subject.write_out
?
Also, I have the reads and writes in a loop, until line[0]
is "quit". Can I test while the loop is running or should I call subject.read_in
and subject.write_out
?
推荐答案
您可以使用模拟并通过在 and_return()
方法中列出多个值来多次调用该方法.这些将按给定的顺序返回,每次调用时返回一个.
You can use mocks and have the method called more than once by listing multiple values in the and_return()
method. These will be returned, one on each call, in the order given.
STDIN.should_receive(:read).and_return("Your string")
STDIN.should_receive(:read).and_return("value1", "value2", "value3")
你可以用 STDOUT 做类似的事情:
You can do similar things with STDOUT:
STDOUT.should_receive(:puts).with("string")
有关详细信息,请参阅 RSpec 模拟文档.
See the RSpec mocking documentation for more information.
这篇关于我可以使用 RSpec 来模拟 stdin/stdout 来测试控制台读取吗?写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!