2013-03-24 85 views
4

我如何存根一個方法,使用rspec需要兩個用戶輸入?可能嗎?rspec - 如何爲多個用戶輸入存根方法?

class Mirror 
    def echo 
     arr = [] 
     print "enter something: " 
     arr[0] = gets.chomp 
     print "enter something: " 
     arr[1] = gets.chomp 

     return arr 
    end 
end 



describe Mirror do 

    it "should echo" do 
     @mirror = Mirror.new 
     @mirror.stub!(:gets){ "foo\n" } 
     @mirror.stub!(:gets){ "bar\n" } 
     arr = @mirror.echo 
     #@mirror.should_receive(:puts).with("phrase") 
     arr.should eql ["foo", "bar"] 

    end 

end 

有了這些功能從@ mirror.echo返回的是[「酒吧」,「杆」]這意味着第一短截線被覆蓋或以其他方式忽略。我也嘗試使用@ mirror.stub!(:gets){「foo \ nbar \ n」}和@ mirror.echo返回[「foo \ nbar \ n」,「foo \ nbar \ n」]]

回答

6

您可以使用and_return方法在每次調用方法時返回不同的值。

@mirror.stub!(:gets).and_return("foo\n", "bar\n") 

而且你的代碼看起來像這樣

it "should echo" do 
    @mirror = Mirror.new 
    @mirror.stub!(:gets).and_return("foo\n", "bar\n") 
    @mirror.echo.should eql ["foo", "bar"] 
end 

使用and_return

counter.stub(:count).and_return(1,2,3) 
counter.count # => 1 
counter.count # => 2 
counter.count # => 3 
counter.count # => 3 
counter.count # => 3