(Rails) update_attributes 在不使用密码的集成测试期间抛出错误(需要密码)

(Rails) update_attributes throws error (needing a password) during integration test that doesn't use password

我正在编写一个 Rails 集成测试来检查用户的标题是否已保存。标题有一个验证:它必须不超过 255 个字符。但是 @user.update_attributes!(title: params[:title]) 抛出错误 "Password must have at least 6 characters." 但是...我没有更新密码或标题以外的任何内容。那么我该如何保存这个带有自己验证的属性而不用担心密码呢?

测试:

  test "profile submits new title and description successfully" do
    log_in_as(@non_admin)
    get user_path(@non_admin)
    assert_nil @non_admin.title
    post "/users/#{@non_admin.id}/update_description",
         { title: "I am a man of constant sorrow." }
    user = assigns(:user)
    user.reload.title
    assert user.title == "I am a man of constant sorrow."
    assert_template 'users/show'
    assert flash[:success]
  end

控制器方法(未完成,但您会明白)。请注意,是 update_attributes! 调用引发了密码验证错误。

  # Handles user's posted title and description.
  def update_description
    @user = User.find(params[:id])
    # Check if title is present. If so, attempt to save, load flash, and reload.
    if @user.update_attributes!(title: params[:title])
      flash[:success] = "Saved title. "
    # if unable, set error flash and reload.
    else
      flash[:warning] = "Unable to save."
    end
    # Same logic as before, now for description.
    # Make sure two different [:success] flashes work! Probably not!
    redirect_to user_path(@user)
  end

验证:

  validates :password, length: { minimum: 6,
                                 message: "must have at least 6 characters" }
  validates :title, length: { maximum: 255 }

测试错误如下:

23:08:51 - INFO - Running: test/integration/users_show_test.rb
Started
ERROR["test_profile_submits_new_title_and_description_successfully", UsersShowTest, 2017-10-23 01:06:11 -0400]
 test_profile_submits_new_title_and_description_successfully#UsersShowTest (1508735171.57s)
ActiveRecord::RecordInvalid:         ActiveRecord::RecordInvalid: Validation failed: Password must have at least 6 characters
            app/controllers/users_controller.rb:71:in `update_description'
            test/integration/users_show_test.rb:22:in `block in <class:UsersShowTest>'
        app/controllers/users_controller.rb:71:in `update_description'
        test/integration/users_show_test.rb:22:in `block in <class:UsersShowTest>'

如果相关,这里是作为 @non_admin:

加载的夹具
archer:
  name: Sterling Archer
  email: duchess@example.gov
  password_digest: <%= User.digest('Jsdfuisd8f') %>
  activated: true
  activated_at: <%= Time.zone.now %>

我是一个 Rails 新手,所以这可能是一些基本知识。提前致谢...

更新:请参阅下面与 kasperite 的讨论。我只需要在我的密码验证中添加 on: create

调用 update_attributes! 将触发 save!,进而触发模型验证。由于您不提供密码,它会抛出异常。

您可以 update_attribute(:title, params[:title]) 绕过验证 或者这个:

    @user.title = params[:title]
    @user.save!(validation: false)

参见:http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update-21