2016-12-05 72 views
0

我嘗試測試更新功能的控制器類:控制器test_should_update:參數是丟失或爲空值

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

是否有人知道我可以從這些燈具容易的數據發送PARAMS因此次在我沒有得到這個錯誤了?我是一個初學者,任何代碼都可以幫助!

回答

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 
+1

作爲一個邊評論:堅持[命名規則](https://github.com/bbatsov/ruby-style-guide)命名變量時。對你的同事和名字變量也很好,不需要評論。 – max

+0

非常感謝!但是當我測試should_create_appointment時,如何傳遞所有屬性?這不工作:post appointments_url,params:{約會:{@ heikoAppointment.attributes}} – Peter

+1

'約會:@ heikoAppointment.attributes'。丟失括號作爲'.attributes'返回一個散列。 – max

相關問題