最良のテストは、達成方法ではなく、達成しようとしていることをテストします... テストを実装に結びつけると、テストが脆弱になります。
したがって、このメソッドで達成しようとしているのは、拡張機能がロードされるたびに「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