我想做的是在命令行上运行ruby sayhello.rb
,然后接收Hello from Rspec
。
我已经明白了:
class Hello
def speak
puts 'Hello from RSpec'
end
end
hi = Hello.new #brings my object into existence
hi.speak
现在我想在 rspec 中编写一个测试来检查命令行输出实际上是“Hello from RSpec” 而不是“我喜欢 Unix”
不工作。我目前在我的 sayhello_spec.rb 文件中有这个
require_relative 'sayhello.rb' #points to file so I can 'see' it
describe "sayhello.rb" do
it "should say 'Hello from Rspec' when ran" do
STDOUT.should_receive(:puts).with('Hello from RSpec')
end
end
有人能给我指出正确的方向吗?
最佳答案
这里有一个很好的方法来做到这一点。复制自 hirb test_helper source :
def capture_stdout(&block)
original_stdout = $stdout
$stdout = fake = StringIO.new
begin
yield
ensure
$stdout = original_stdout
end
fake.string
end
像这样使用:
output = capture_stdout { Hello.new.speak }
output.should == "Hello from RSpec\n"
关于ruby - 使用 RSpec 测试输出到命令行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11349270/