2011-09-21 27 views
0

這裏是RSpec的誤差:使用RSpec誤差在控制器創建

CategoriesController GET 'update' should be successful 
Failure/Error: get 'update' 
ActiveRecord::RecordNotFound: 
    Couldn't find Category without an ID 
# c:in `find' 
# ./app/controllers/categories_controller.rb:45:in `update' 
# ./spec/controllers/categories_controller_spec.rb:35:in `block (3 levels) in <top (required)>' 

這裏是在控制器的代碼:

def edit 
    @category = Category.find(params[:id]) 
    end 

    def update 
    @category = Category.find(params[:id]) 
    #@category.reload. caused nil.reload error 

    if @category.update_attributes(params[:category], :as => :roles_update) 
     @category = Category.find(params[:id]) 
     redirect_to @category, :notice => 'Category was successfully updated' 
    else 
     @categories = Category.all 
     render 'index' 
    end 
    end 

這裏是RSpec的代碼:

describe "GET 'update'" do 
    it "should be successful" do 
     get 'update' 
     response.should be_success 
    end 
    end 

有什麼想法嗎?謝謝。

回答

1

您粘貼了創建操作而不是更新操作。此外,您正在嘗試使用get請求測試更新操作。如果遵循約定,它應該與put請求一起使用。

如果你有,說,更新操作實現......你會測試或多或少是:

describe CategoriesController do 
    let(:category) { mock_model(Category).as_null_object } 

    describe "PUT update" do 
    before do 
     Category.should_receive(:find).with(5).and_return(category) 
    end 

    context "when a category updates succesfully" do 
     before do 
     category.stub(:update_attributes).and_return(true) 
     end 

     it "redirects to the categories page" do 
     put :update, :id => 5, :category => { :some_val => 4 } 
     response.should redirect_to(categories_path) 
     end 

     it "sets the flash message" do 
     put :update, :id => 5, :category => { :some_val => 4 } 
     flash[:notice].should eq("Category was succesfully updated") 
     end 
    end 

    context "when a category does not update successfully" do 
     before do 
     category.stub(:update_attributes).and_return(false) 
     end 

     it "sets the flash message" 
     it "redirects to the categories page" 

     # etc etc 
    end 
    end 
end 

爲了得到這一點(指除模擬模型,存根,你有什麼的)你通常會開始「新鮮」,這樣可以說話並按照TDD風格工作。希望它有幫助

+0

發佈了方法更新和編輯。將測試您的解決方案。謝謝。 – user938363

+0

如果你要使用示例代碼我張貼,你應該改變 response.should redirect_to的(categories_path) 被更新的類路徑(這是您在更新行動在做什麼) –

+0

仍在努力。表中有幾個類別記錄,我只是選擇其中的一個,在rspec中「更新,:id => 2,:category => {:active => false}」。仍然有ActiveRecord :: RecordNotFound:無法找到id = 2的類別。但是我可以在Rail控制檯中用Category.find(2)來取出記錄。 – user938363