Search code examples
ruby-on-railshttp-redirectrspecnested-routes

Rails 4.1 nested routes redirect_to test won't pass


Just getting comfortable with Rails but this one has stumped me. Thanks for the help!

Here is the current failing test.

Failures:

  1) SectionsController POST #create with valid attributes redirects to course_section_path
     Failure/Error: expect(response).to redirect_to course_section_path
     ActionController::UrlGenerationError:
       No route matches {:action=>"show", :controller=>"sections"} missing required keys:  [:course_id, :id]
     # ./spec/controllers/sections_controller_spec.rb:59:in `block (4 levels) in <top (required)>'

Finished in 0.12643 seconds (files took 1.77 seconds to load)

Iv'e tried so many things to provide the redirect with the proper params but nothings seems to work. Help!! Thank you!

Rspec Test

  it "redirects to course_section_path" do
        post :create, section: attributes_for(:section)
        expect(response).to redirect_to course_section_path
  end

controller: sections#show, section#create, and strong paramaters.

def create
    @section = Section.new(section_params)
    if @section.save 
        flash[:success]="New section added!"
        redirect_to course_section_path(@section.course_id, @section.id)
    else
        flash[:error] = "There was an error creating the section."
        render action: :new
    end
end

def show 
    @course = Course.find(params[:course_id])
    @section = @course.sections.find(params[:id])
end

private

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

Factory

factory :section do
    name "Section One"
    course_id 1
end

Database Scheema

  create_table "courses", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "sections", force: true do |t|
    t.string   "name"
    t.integer  "course_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

Routes

  resources :courses
  resources :sections

  resources :courses do
    resources :sections
  end

Solution

  • Ok I figured this one out!

    The line

    post :create, section: attributes_for(:section)
    

    creates a record in the database, which when assigned to a variable, can be used to test with.

    section = Section.last
    

    Then going with what Szymon Borucki said, I provided the course_id and the Id needed to call the route.

    expect(response).to redirect_to course_section_path(course_id: section.course_id, id: section.id)
    

    AND it works!!

    Here is the whole working test!

    it "redirects to course_section_path" do
            post :create, section: attributes_for(:section)
            section = Section.last
            expect(response).to redirect_to course_section_path(course_id: section.course_id, id: section.id)
        end