传递隐藏字段时无法测试控制器

Can't test a controller when passing a hidden field

我有两个对象,Course 和 TeacherRight。我创建了 TeacherRight,并在课程 'show' 视图上放置了一个 from。我将 course_id 作为隐藏字段传递给 TeacherRight 控制器:

=form_for(@right) do |f|
  =hidden_field_tag :course_id, @course.id
  %ul
    %li=f.collection_select :user_id, User.order(:name)-@course.teachers, :id, :name, include_blank: false
    %li=f.submit 

控制器:

class TeacherRightsController < ApplicationController

  def create
    course = Course.find(params[:course_id])
    @teacher_right = course.teacher_rights.build(teacher_right_params)
    @teacher_right.save
    redirect_to course
  end

  private
    def teacher_right_params
      params.require(:teacher_right).permit(:user_id)
    end
  #only owner can add teachers to course
  def can_edit(course)
    redirect_to root_url unless current_user == course.owner
  end

它工作正常,但我不能为它编写测试!我写了

class TeacherRightsControllerTest < ActionController::TestCase
  def setup
    @owner_1 = users(:owner_1)
    @course = courses(:course)
    @teacher_1 = users(:teacher_1)
  end

  test "teacher can't add teachers" do
    log_in_as(@teacher_1)
    assert_no_difference('TeacherRight.count') do
      post :create, {teacher_right: {course_id:@course.id, user_id: @teacher_1.id }}
    end
  end

但是报错:

ActiveRecord::RecordNotFound: Couldn't find Course with 'id'=
            app/controllers/teacher_rights_controller.rb:4:in `create'

如我所见,

post :create, {teacher_right: {course_id:@course.id, user_id: @teacher_2.id, }} 

不会以控制器可以使用的方式传递 course_id。我该如何更正它?

您不小心在 :teacher_right 散列中发布了 :course_id,因此它将显示为 params[:teacher_right][:course_id] 而不是所需的 params[:course_id].

您的 POST 请求应如下所示:

post :create, {
  course_id: @course.id,
  teacher_right: { user_id: @teacher_1.id }
}