controller_test:NoMethodError:未定义的方法`permit&#39;对于#<array:0x98583f0>

时间:2016-12-05 22:43:52

标签: ruby-on-rails unit-testing

我尝试测试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'

1 个答案:

答案 0 :(得分:2)

问题在于您在测试中将params传递给post请求的方式。在params哈希中,除appointmentinvitation_attributesaction以及controller等特定于表单的实体外,还有两个键authenticity tokenencoding }。

当您的测试运行时,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哈希中的内容。