あなたの最初の質問については「少し鮮明にする方法」、私たちはモックを使用しないことから始めました。
モックオブジェクトは、重要ではないがテストケースに存在しなければならないオブジェクトである、第2オブジェクトの予測可能な動作に依存できない場合に便利です。モックオブジェクトの典型的な使用例は、データベースクエリ、ネットワーク使用法、ファイルI/Oです。コンピュータのネットワーク接続が失われたか、データベースが使用できないため、テストが失敗しないようにします。
rails g scaffold
から得た生成コードは最適ではありません。生成されたコードは、すべてのテストを通過させる方法で生成されました。そのために、モックオブジェクトを使用します。私は彼らがなぜそれをするのかわからない、私はより良いデフォルトは、あなたが実際に何かを行う必要があるようにテストを失敗すると思うそれらを渡すには。
私は生成されたモックを削除し、次のようなものだろう:私たちはモックオブジェクトを使用していない、ので、コードはいくつかのパラメータとPOSTの呼び出しを行うとことを確認するに縮小され
#spec/controllers/weather_controller_spec.rb
describe "POST create" do
describe "with valid params" do
it "assigns a newly created weather as @weather" do
post :create, :weather => {'location' => 'ORD', 'temp'=>'35', 'sample_time'=>'2011-02-04T20:00-0500'}
assigns(:weather).should be_valid
end
it "should redirect you to the weather show page" do
post :create, :weather => {'location' => 'ORD', 'temp'=>'35', 'sample_time'=>'2011-02-04T20:00-0500'}
response.should redirect_to(weather_path(assigns[:weather]))
end
end
describe "without valid params" do
it "should notify that a location is required" do
post :create, :weather => {'temp'=>'35', 'sample_time'=>'2011-02-04T20:00-0500'}
flash[:notice].should == 'Location is required.'
assigns(:weather).should_not be_valid
end
it "should notify that a temperature is required" do
post :create, :weather => {'location' => 'ORD', 'sample_time'=>'2011-02-04T20:00-0500'}
flash[:notice].should == 'A temperature is required.'
assigns(:weather).should_not be_valid
end
it "should notify that a sample time is required" do
post :create, :weather => {'location' => 'ORD', 'temp'=>'35'}
flash[:notice].should == 'A sample time is required.'
assigns(:weather).should_not be_valid
end
end
end
お知らせオブジェクトは有効です。モデルファイルにバリデーションルールを記述しなければならないので、モックオブジェクトを使用していないので、実際のバリデーションが行われていることを確認できます。
自動生成モックファイルでは、何もする必要はありません。テストは永遠に続きます。それは悪い考え、悪い習慣です。
また、パラメータが無効であるか不足している場合を実行するテストをさらに作成する必要があることにも注意してください。また、assigns(:weather).should_not be_valid
を実行することで、検証が自分の仕事をしていることを確認しています。
post :create
に電話するたびにパラメータ辞書を書くことは繰り返し、壊れやすく醜いです。あなたは器具の使い方を学ぶべきです。たとえば、あなたが再利用可能な、より読みやすいコードを与えるファクトリー・ガール
#spec/factories.rb
Factory.define :weather_valid do |f|
f.location "ORD"
f.temp "35"
f.sample_time "2011-02-04T20:00-0500"
end
#spec/controllers/weather_controller_spec.rb
describe "POST create" do
describe "with valid params" do
it "assigns a newly created weather as @weather" do
post :create, :weather => Factory.build(:weather_valid).attributes
assigns(:weather).should be_valid
end
it "should redirect you to the weather show page" do
post :create, :weather => Factory.build(:weather_valid).attributes
response.should redirect_to(weather_path(assigns[:weather]))
end
end
...
と。
ありがとうございます。あなたの例は、事柄を非常に明確にしています。 – alenm