2012-03-31 103 views
0

我想學習TDD,這是我作業的一部分,我無法弄清楚如何去做。Rspec創建控制器操作的測試有什麼問題?

我想測試create控制器動作,這裏是我的測試代碼:

require 'spec_helper' 

describe MoviesController do 
    describe 'create' do 
    it 'should call the model method perform create!' do 
     Movie.should_receive(:create!).with({"title" => 'Milk', "rating" => 'R'}) 
     post :create, :movie => {:title => 'Milk', :rating => 'R'} 
    end 
    end 
end 

但我得到:

Failures: 

    1) MoviesController create should call the model method performe create! 
    Failure/Error: post :create, :movie => {:title => 'Milk', :rating => 'R'} 
    NoMethodError: 
     undefined method `title' for nil:NilClass 
    # ./app/controllers/movies_controller.rb:50:in `create' 
    # ./spec/controllers/movies_controller_spec.rb:7:in `block (3 levels) in <top (required)>' 

Finished in 0.21714 seconds 

這裏是創建行動,我對測試。是的,這是TDD,是的,我測試 工作代碼,並且它的測試不工作:d

def create 
    @movie = Movie.create!(params[:movie]) 
    flash[:notice] = "#{@movie.title} was successfully created." 
    redirect_to movies_path 
end 

我甚至不知道爲什麼我得到了未定義的方法錯誤訊息?我還有其他幾個測試通過了,但爲了簡單起見,我在這段代碼片段中刪除了,所以我不認爲它與db/model相關的配置問題有關。但爲什麼它不工作,以及如何改變它?

乾杯

回答

0

當你做這樣的一個should_receive,所以下一行(將閃光燈設置消息時)試圖檢索從零標題將返回零。您should_receive更改爲:

Movie.should_receive(:create!).with({"title" => 'Milk', "rating" => 'R'}).and_return(stub_model(Movie)) 
+0

Should_receive將返回零,即使它沒有收到的匹配參數「{」標題「=>‘牛奶’,‘等級’=>‘R’}」,所以我需要趕上返回值,我知道了嗎? – 2012-03-31 03:22:20

+0

對不起,我現在明白了,它來自控制器線。謝謝@ctide,拯救了我的一天! – 2012-03-31 03:28:53