Reputation: 59
I have two objects, Course and TeacherRight. I create TeacherRight with a from placed on the Course 'show' view. I pass course_id to the TeacherRight controller as a hidden field:
=form_for(@right) do |f|
=hidden_field_tag :course_id, @course.id
%ul
%li=f.collection_select :user_id, User.order(:name)[email protected], :id, :name, include_blank: false
%li=f.submit
The controller:
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
It works fine, but I can't write a test for it! I wrote
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
But it gives an error:
ActiveRecord::RecordNotFound: Couldn't find Course with 'id'=
app/controllers/teacher_rights_controller.rb:4:in `create'
As I can see,
post :create, {teacher_right: {course_id:@course.id, user_id: @teacher_2.id, }}
doesn't pass course_id in a way the controller can consume. How can I correct it?
Upvotes: 0
Views: 59
Reputation: 271
You accidentally are posting the :course_id
inside the :teacher_right
hash, so it will show up as params[:teacher_right][:course_id]
instead of the desired params[:course_id]
.
Your POST request should look like this:
post :create, {
course_id: @course.id,
teacher_right: { user_id: @teacher_1.id }
}
Upvotes: 2