16
17

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で標準出力をテストしたい

Posted at

ここにまんま書いてあったので試してみる。

->RSpecで標準出力の内容をテストする

hello_spec.rb
require 'stringio'

class Hello
	def hello
		puts "hello"
	end
end

def capture(stream)
	begin
		stream = stream.to_s
		eval "$#{stream} = StringIO.new"
		yield
		result = eval("$#{stream}").string
	ensure
		eval "$#{stream} = #{stream.upcase}"
	end
	result
end

describe "Hello#helloは'hello'と標準出力すること"
	@target = Hello.new
	
	capture(:stdout) { @target.hello }.should == 'hello\n'
		
end

rspecにかけてみる

>rspec hello_spec.rb
Finished in 0.00007 seconds
0 examples, 0 failures

素晴らしい。
なぜか 'stringio' をrequireしないと動かなかった。

16
17
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
16
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?