【问题标题】:rspec - How can I stub a method with multiple user inputs?rspec - 如何存根具有多个用户输入的方法?
【发布时间】:2013-03-14 08:26:37
【问题描述】:

如何使用 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 的返回值是 ["bar", "bar"],这意味着第一个存根被覆盖或以其他方式忽略。

我也尝试过使用@mirror.stub!(:gets){"foo\nbar\n"} 并且@mirror.echo 返回 ["foo\nbar\n","foo\nbar\n"]

【问题讨论】:

    标签: ruby rspec stub


    【解决方案1】:

    您可以使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-15
      • 2015-08-31
      • 2019-06-08
      • 2013-03-01
      • 1970-01-01
      • 2011-09-29
      • 2013-06-22
      相关资源
      最近更新 更多