2012-07-25 106 views
0

我对用户输入的代码:测试输入输出

class Z 
    def self.input() 
    val = $stdin.gets.chomp 
    if val == "123" 
     p "Ok" 
    else 
     p "none" 
    end 
    end 
end 

我想测试不同的数据:

describe "Z" do 
    it "should receive none" 
    Object.stub!(:gets){"das"} 
    Z.input 
    Object.should_receive(:p).with("none") 
    end 
end 

,但我得到一个错误:

Failure/Error: Object.should_receive(:p).with("none") 
    (<Object (class)>).p("none") 
     expected: 1 time 
     received: 0 times 

如何测试输出? 谢谢。

回答

0

试试这个:

describe Z do 
    it "should print into stdout" do 
    $stdin.stub(:gets).and_return("das") 
    $stdout.should_receive(:p).with("none") 
    Z.input 
    end 
end 
+0

我得到的错误'故障/错误:$ stdout.should_receive(:P)。随着( “无”) (#),P(“无“) 预计:1次 收到:0次 ' – Mike 2012-07-25 11:21:38

+0

我解决了这个问题。 Object.stub!(:gets){“das”} Object.should_receive(:p).with(“none”) Z.input ' – Mike 2012-07-25 11:23:00

+0

在对象上存根不是个好主意,试试用STDIN和STDOUT代替$ stdin和$ stdout – megas 2012-07-25 11:27:06