【问题标题】:Rails 4 Params missing, Rspec testing nested resources controller update methodRails 4 Params 缺失,Rspec 测试嵌套资源控制器更新方法
【发布时间】:2014-10-21 20:04:57
【问题描述】:

这里是 Rails 新手,

我理解错误,但我不明白为什么我的测试没有通过。我也不知道如何查看传递给操作的参数哈希,所以调试对我来说有点混乱。

测试失败

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)>'

测试

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

节控制器更新方法

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

路线

resources :courses do
    resources :sections
end

型号

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

感谢您的帮助!

【问题讨论】:

  • 试试这个看看是否修复:post :update, course_id: @section.course_id, id: @section.id, section: {name: @section.name,course_id: @section.course_id}
  • 成功了!非常感谢你,很抱歉回复晚了,我整个周末都不在家。所以我错过了它看起来像的部分的属性?
  • 好的,我会发布一个答案供您接受。

标签: testing ruby-on-rails-4 rspec controller


【解决方案1】:

使用所有必需参数进行帖子的正确方法如下:

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

【讨论】:

  • 这并不能解决问题。问题是关于使用 PATCH。 POST 用于新对象。 PATCH 用于增量 PUT(更新)
猜你喜欢
  • 1970-01-01
  • 2012-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多