3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2015-09-23

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
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?