Can I use RSpec to mock stdin/stdout to test console reads & writes?

怎甘沉沦 提交于 2019-12-17 16:26:17

问题


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

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?


回答1:


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")

You can do similar things with STDOUT:

STDOUT.should_receive(:puts).with("string")

See the RSpec mocking documentation for more information.




回答2:


RSpec 3.0+

With RSpec 3.0, there is output matcher for this purpose:

expect { my_method }.to output("my message").to_stdout
expect { my_method }.to output("my error").to_stderr


来源:https://stackoverflow.com/questions/6335282/can-i-use-rspec-to-mock-stdin-stdout-to-test-console-reads-writes

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