ruby - 使用 RSpec 测试输出到命令行

标签 ruby testing rspec

我想做的是在命令行上运行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/

相关文章:

ruby-on-rails - 电子邮件未在 RoR 应用程序中发送

python - 所有动态语言都有循环导入问题吗?

xml - XML测试脚本/运行器

laravel - 使用 Laravel5 模块 : withoutWrapping() applied on single JsonResource affects other tests 进行 Codeception api 测试

testing - 如何为 karma e2e 设置 jasmine 以测试 Angular 应用程序?

ruby-on-rails - capybara 及之前(:all) in rspec

ruby - 如何将 boolean 值转换为整数?

ruby - 如何让代码跳转到整段代码的任意一个地方?

ruby-on-rails - 在单元测试 Rails 模型中使用 shoulda-matchers 还是 Factory Girl 更好?

ruby - RSpec 为/lib 的子目录中的代码引发 NameErrors