Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby rspec-如何使用多个用户输入来存根一个方法?_Ruby_Rspec_Stub - Fatal编程技术网

Ruby rspec-如何使用多个用户输入来存根一个方法?

Ruby rspec-如何使用多个用户输入来存根一个方法?,ruby,rspec,stub,Ruby,Rspec,Stub,如何使用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

如何使用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”]

每次调用该方法时,可以使用该方法返回不同的值

@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
使用
和_return

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