0

私はRSpecとTDDを初めて使用します。このモジュールに適したテストを作成するのを誰かが手伝ってくれるのではないかと思っていました。

module Kernel
  # define new 'puts' which which appends "This will be appended!" to all puts output 
  def puts_with_append *args
    puts_without_append args.map{|a| a + "This will be appended!"}
  end

  # back up name of old puts
  alias_method :puts_without_append, :puts

  # now set our version as new puts
  alias_method :puts, :puts_with_append
end

「puts」の内容が「Thiswillappled!」で終わることをテストで確認したいのですが。それで十分なテストでしょうか?どうすればいいですか?

4

1 に答える 1

2

最良のテストは、達成方法ではなく、達成しようとしていることをテストします... テストを実装に結びつけると、テストが脆弱になります。

したがって、このメソッドで達成しようとしているのは、拡張機能がロードされるたびに「puts」に変更することです。メソッド puts_with_append をテストしても、この目標は達成されません... 後で誤ってそれを別のものに再エイリアスすると、目的の puts の変更は機能しません。

ただし、実装の詳細を使用せずにこれをテストするのはかなり難しいため、代わりに、STDOUTなど、変更されない場所に実装の詳細をプッシュすることができます。

テスト内容のみ

$stdout.stub!(:write)
$stdout.should_receive(:write).with("OneThis will be appended!")
puts "One"

総テスト

翌日かそこらでこれをブログ投稿に変える予定ですが、1 つおよび多くの引数に対して望ましい結果が得られていること、およびテストが読みやすいものであることも考慮する必要があると思います。私が使用する最終的な構造は次のとおりです。

"rspec" が必要 "./your_extention.rb" が必要

describe Kernel do
  describe "#puts (overridden)" do
    context "with one argument" do
      it "should append the appropriate string" do
        $stdout.stub!(:write)
        $stdout.should_receive(:write).with("OneThis will be appended!")
        puts "One"
      end
    end

    context "with more then one argument" do
      it "should append the appropriate string to every arg" do
        $stdout.stub!(:write)
        $stdout.should_receive(:write).with("OneThis will be appended!")
        $stdout.should_receive(:write).with("TwoThis will be appended!")
        puts("One", "Two")
      end
    end
  end
end
于 2013-01-10T01:46:18.033 に答える