標準出力での文字列の受信をテストするために、Rspec でできる最も基本的なテストを作成しようとしました。
次のように、RSpec Book に書かれているのとまったく同じ方法で、標準出力をスチューブしました。
require './tweetag.rb'
module Tweetag
describe Tweet do
describe "#print" do
it "prints test" do
output = double('output').as_null_object
t = Tweetag::Tweet.new(output)
t.print
output.should_receive(:puts).with('test')
end
end
end
end
Ruby コードは次のようになります。
module Tweetag
class Tweet
def initialize(output)
@output=output
end
def print
@output.puts('test')
end
end
end
ご覧のとおり、特に複雑なことは何もありません。それでも、仕様を実行した後に受け取る答えは次のとおりです。
Failures:
1) Tweetag::Tweet#print prints test
Failure/Error: output.should_receive(:puts).with('test')
(Double "output").puts("test")
expected: 1 time
received: 0 times
「as_null_object」を削除しようとしましたが、答えは次のとおりです。
1) Tweetag::Tweet#print prints test
Failure/Error: t.print
Double "output" received unexpected message :puts with ("test")
ご協力ありがとうございました。