ここにまんま書いてあったので試してみる。
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しないと動かなかった。