Jacksonvoice
Jacksonvoice

Reputation: 93

Rails 4 Params missing, Rspec testing nested resources controller update method

New to rails here,

I understand the error but I don't get why my test isn't passing. I also don't know how to look at the params hash that is being passed into the action either, so debugging is kinda confusing for me.

Failing test error

1) SectionsController PATCH #update with valid attributes finds the correct course.section assigns @section
     Failure/Error: patch :update, course_id: @section.course_id, id: @section.id
     ActionController::ParameterMissing:
       param is missing or the value is empty: section
     # ./app/controllers/sections_controller.rb:52:in `section_params'
     # ./app/controllers/sections_controller.rb:36:in `update'
     # ./spec/controllers/sections_controller_spec.rb:95:in `block (4 levels) in <top (required)>'

Test

describe "PATCH #update" do
    context "with valid attributes" do
      before :each do 
          @course = create(:course)
          @section = create(:section, name: "section1")
      end
      it "finds the correct course.section & assigns @section" do 
        patch :update, course_id: @section.course_id, id: @section.id
        expect(assigns(:section)).to eq(@section)
      end
    end
end

Section Controller update method

def update
    @course = Course.find(params[:course_id])
    @section = Section.find(params[:id])
      if @section.update_attributes(section_params)
      flash[:success] = "the section has been updated"
      redirect_to [@course, @section]
    else
      flash[:error] = "you must enter the correct information"
      render action: "edit"
    end
  end

private 

  def section_params
    params.require(:section).permit(:name, :course_id) 
  end
end

Routes

resources :courses do
    resources :sections
end

Models

class Section < ActiveRecord::Base
    belongs_to :course
    validates :name, :course_id, presence: true
end

class Course < ActiveRecord::Base
    has_many :sections
    accepts_nested_attributes_for :sections
    validates :name, presence: true
end

Thank you for any help!

Upvotes: 0

Views: 1592

Answers (1)

Alireza
Alireza

Reputation: 2691

The correct way to do a post with all the required parameters is as follows:

post :update, course_id: @section.course_id, id: @section.id, section: {name: @section.name,course_id: @section.course_id}

Upvotes: 4

Related Questions