0

標準出力での文字列の受信をテストするために、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")

ご協力ありがとうございました。

4

1 に答える 1

2

should_receiveメソッドは、実際にメソッドを呼び出す前に使用する必要があります。

output = double('output').as_null_object
t = Tweetag::Tweet.new(output)
output.should_receive(:puts).with('test')
t.print

補足として、テストには戻り値のチェックがありません。print メソッドは例外を発生させません。ただし、戻り値が適切であることを確認しません。

output.should_receive(:puts).with('test').and_return('returned value')
t.print.should eql('returned value')
于 2013-07-17T16:02:53.757 に答える