controller test_should_update:param丢失或值为空

时间:2016-12-05 16:56:53

标签: ruby-on-rails unit-testing

我尝试在控制器类中测试更新功能:

require 'test_helper'

class AppointmentsControllerTest < ActionDispatch::IntegrationTest
  include Devise::Test::IntegrationHelpers
  include Warden::Test::Helpers

  setup do
    @heikoAppointment = appointments(:appointment_heiko)
    @heiko = users(:user_heiko)
  end

 test "should update appointment" do
    login_as(@heiko)
    @heiko.confirmed_at = Time.now
    patch appointment_url(@heikoAppointment), params: { appointment: {  } }
    assert_redirected_to appointment_url(@heikoAppointment)
  end

但是我收到了这个错误:

ActionController::ParameterMissing: param is missing or the value is empty: appointment

在灯具中我保存了一些预约数据:

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] %>

有人知道如何轻松地从灯具发送带有这些数据的参数,这样我就不会再出现这个错误了吗?我是初学者,任何代码都可以提供帮助!

1 个答案:

答案 0 :(得分:1)

您收到错误,因为appointment键包含空哈希且未发送。

要从您可以使用的模型中获取属性 - 您猜对了 - .attributes

因此@heikoAppointment.attributes将为您提供模型中的属性。

但是在测试更新方法时,您应该只传递要更新的属性并声明它们已被更改。

您还应该测试不会更改任何不可修改的属性。

before do
  login_as(@heiko)
end

test "should update appointment" do
  @heiko.confirmed_at = Time.now
  patch appointment_url(@heikoAppointment), params: { appointment: { foo: 'bar' } }
  assert_redirected_to appointment_url(@heikoAppointment)
end

test "should update appointment foo" do
  patch appointment_url(@heikoAppointment), 
        params: { appointment: { foo: 'bar' } }
  @heikoAppointment.reload # refreshes model from DB
  assert_equals( 'bar', @heikoAppointment.foo )
end 

test "should not update appointment baz" do
  patch appointment_url(@heikoAppointment), 
          params: { appointment: { baz: 'woo' } }
  @heikoAppointment.reload # refreshes model from DB
  assert_not_equal( 'woo', @heikoAppointment.foo )
end