Rails 4.1嵌套路由redirect_to test不会通过

时间:2014-10-15 21:42:25

标签: ruby-on-rails redirect rspec nested-routes

对Rails感到满意但是这个让我难过。谢谢你的帮助!

这是当前失败的测试。

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)
我试过这么多东西来提供重定向和正确的参数,但是看起来没什么用。救命!!谢谢!

Rspec测试

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

控制器:部分#show,部分#create和强参数。

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 :section do
    name "Section One"
    course_id 1
end

数据库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

路线

  resources :courses
  resources :sections

  resources :courses do
    resources :sections
  end

2 个答案:

答案 0 :(得分:1)

因为'sections'是'courses'中的嵌套资源,所以你需要提供带有path_section_path路径的course_id和section_id参数。尝试这样的事情:

  it "redirects to course_section_path" do
        course = create(:course) #if you use Factories
        post :create, section: attributes_for(:section)
        expect(response).to redirect_to course_section_path(course_id: course.id, id: section.id)
  end

答案 1 :(得分:1)

好的,我想出了这个!

该行

post :create, section: attributes_for(:section)

在数据库中创建一条记录,当分配给变量时,可以用来测试。

section = Section.last

然后继续Szymon Borucki说的话,我提供了course_id和Id所需的呼叫路线。

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

它有效!!

这是整个工作测试!

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