ぼろぼろ平原

困った

RSpecで「while line = gets」をテストする方法

RSpecwhile line = getsのような標準入力のループをテストしたいとき。

Kernel.#getsARGFをレシーバとしたメソッドの省略形なので、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