user938363
user938363

Reputation: 10350

rspec error with create in controller

Here is the error in 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)>'

Here is the code in controller:

  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

Here is the rspec code:

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

Any thoughts? Thanks.

Upvotes: 0

Views: 917

Answers (1)

You pasted the create action instead of the update action. Also, you are trying to test the update action with a get request.. it should be with a put request if you are following the conventions.

If you had, say, the update action implemented... you would test more or less like:

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

To get to this point (meaning the addition of mock models, stubs, what have you) you would normally start "fresh" so to speak and work your way up TDD style. Hope it helps

Upvotes: 1

Related Questions