【问题标题】:How to verify that "puts" has been called with a certain message?如何验证是否已使用特定消息调用了“puts”?
【发布时间】:2025-11-27 08:20:02
【问题描述】:

我试图让这个测试失败:)

it "should display the question" do
  @ui.should_receive(:puts).with("What's your name?").once
  @ui.ask_question("What's your name?")
end

即使我没有在我的函数中调用 puts,它也会通过。

【问题讨论】:

  • 你的方法 ask_question 中的代码是什么?

标签: ruby mocking rspec


【解决方案1】:

基本上,@ui 应该在一个可能默认为 $stdout 的对象上调用 .puts。然后在您的测试中,您可以将 $stdout 替换为可以设置期望的 StringIO 对象。这还有一个额外的好处,就是让你的 @ui 对象更加灵活。

【讨论】:

  • 你能给我一个替换 $stdout 的例子吗?
【解决方案2】:

给定代码:

require 'rubygems'
require 'spec'

class UI
  def ask_question(q)
  end
end

describe UI do
  before do
    @ui = UI.new
  end

  it "should display the question" do
    @ui.should_receive(:puts).with("Whats your name?").once
    @ui.ask_question("Whats your name?")
  end
end

我失败了:

F

1) Spec::Mocks::MockExpectationError in 'UI should display the question'
#<UI:0xb738effc> expected :puts with ("Whats your name?") once, but received it 0 times /home/avdi/tmp/puts_spec.rb:15:

Finished in 0.002575 seconds

1 example, 1 failure

您使用的是什么版本的 RSpec?

【讨论】:

  • 有趣!我正在使用 rspec 2 beta 可能是新版本的问题。我将尝试使用较旧的 rspec。
【解决方案3】:

你可以试试stringioZenTest,下面的ruby-talkthread有更多信息。

【讨论】:

    最近更新 更多