RSpecでwhile line = getsのような標準入力のループをテストするには以下のコードを書く。
getsはEOFが入力された時には(EOFに到達した時には)nilを返すので、["line1", "line2", nil]のような配列を使う。
テストしたいコード:
def foo
ary = []
while line = gets
ary << line.chomp
end
ary
end
テストコード:
it "標準入力を行ごとに配列にして返す" do
inputs = ["line1", "line2", nil].to_enum
allow(ARGF).to receive(:gets) { inputs.next }
expect(foo).to contain_exactly("line1", "line2")
end
同様に、while line = Readline.readlineなどの場合にもこの方法は使える。
テストしたいコード:
def bar
ary = []
while line = Readline.readline
ary << line.chomp
end
ary
end
テストコード:
it "標準入力を行ごとに配列にして返す" do
inputs = ["line1", "line2", nil].to_enum
allow(Readline).to receive(:readline) { inputs.next }
expect(bar).to contain_exactly("line1", "line2")
end