RSpecで「while line = gets」をテストする方法
RSpecでwhile line = gets
のような標準入力のループをテストしたいとき。
Kernel.#gets
はARGF
をレシーバとしたメソッドの省略形なので、ARGF.gets
をモックにすれば良い。
テストしたいコード:
# 標準入力を行ごとに区切って配列にするメソッド def foo ary = [] while line = gets ary << line.chomp end ary end
テストコード:
require "rspec" require "stringio" require_relative "foo" describe "foo" do it "標準入力を行ごとに区切って配列にする" do inputs = StringIO.new("line1\nline2\n") allow(ARGF).to receive(:gets) { inputs.gets } expect(foo).to contain_exactly("line1", "line2") end end