2010-03-29 40 views
3

我试图使这个测试失败:)如何验证“puts”是否被某个消息调用?

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

此时即使我不叫我的函数将它传递的那一刻。

+0

什么是你在你的方法ask_question代码? – shingara 2010-03-29 06:56:05

回答

3

基本上,@ui应该调用标准输出的.puts对象上可能默认为$。然后在你的测试中,你可以用你可以设置期望值的StringIO对象替换$ stdout。这有助于使您的@ui对象更加灵活。

+1

你可以给我一个替换$ stdout的例子吗? – soulnafein 2010-03-30 07:30:18

1

给予代码:

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您使用的是?

+0

有趣!我正在使用rspec 2测试版,可能这是新版本的问题。我将尝试使用旧的rspec。 – soulnafein 2010-03-30 21:12:16