我尝试测试should_create_appointment块。这是代码: 的 appointments_controller_test.rb
.....
test "should create appointment" do
login_as(@heiko)
@heiko.confirmed_at = Time.now
assert_difference('Appointment.count') do
post appointments_url, params: { appointment: [@heikoAppointment.attributes, @heikoInvitation.user_id, @heikoInvitation.message] }
end
assert_redirected_to appointment_url(Appointment.last)
end
...
控制器/ appointments_controller.rb
def appointment_params
params.require(:appointment).permit(:shopper_id, :status, :appointed, :processed, :shopping_list_id, invitation_attributes: [:user_id, :message ])
end
然而,当我运行测试时,我在should_create_appointment:
中收到此错误AppointmentsControllerTest#test_should_create_appointment:
NoMethodError: undefined method `permit' for #<Array:0x98583f0>
app/controllers/appointments_controller.rb:141:in `appointment_params'
test/controllers/appointments_controller_test.rb:31:in `block (2 levels) in <class:AppointmentsControllerTest>'
test/controllers/appointments_controller_test.rb:30:in `block in <class:AppointmentsControllerTest>'
有人知道出了什么问题吗?这是固定装置:
appointments.yml
appointment_heiko:
user: user_heiko
appointed: <%= Time.now + 2.weeks %>
processed: <%= Time.now - 1.weeks %>
shopping_list: shopping_list_lebensmittel
shopper: user_shopper
status: <%= Appointment.statuses[:finished] %>
invitations.yml
invitation_heiko:
user: user_heiko
shopping_list: shopping_list_drogerie
appointment: appointment_heiko
accepted: true
responded: <%= Time.now - 3.weeks %>
message: 'Gerne akzeptiere ich die Einladung'
答案 0 :(得分:2)
问题在于您在测试中将params
传递给post
请求的方式。在params哈希中,除appointment
,invitation_attributes
和action
以及controller
等特定于表单的实体外,还有两个键authenticity token
和encoding
}。
当您的测试运行时,params.require(:appointment)
将返回一个数组。 permit
是一种适用于hashes
而非arrays
的方法。这清楚地表明params[:appointment]
应该是hash
。
post appointments_url, params: { appointment: @heikoAppointment.attributes, invitation_attributes: { user_id: @heikoInvitation.user_id, message: @heikoInvitation.message } }
要实际查看传入的内容,请使用以下内容替换create
操作。
def create
render text: appointment_params
end
现在,如果您尝试通过提交表单来创建新实体,您将发现服务器以纯文本形式发送的参数。这应该可以了解params
哈希中的内容。