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

后端 未结 2 1601
悲哀的现实
悲哀的现实 2020-12-09 20:27

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?

相关标签:
2条回答
  • 2020-12-09 20:35

    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
    
    0 讨论(0)
  • 2020-12-09 20:47

    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.

    0 讨论(0)
提交回复
热议问题