2012-07-25 90 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