我正在编写一个 Rails 集成测试来检查用户的标题是否保存。标题有一个验证:它必须不超过 255 个字符。但是@user.update_attributes!(title: params[:title])
抛出错误“密码必须至少有6个字符”。但是...我不会更新密码或标题以外的任何内容。那么如何通过自己的验证保存这个属性而不用担心密码呢?
测试:
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: [email protected]
password_digest: <%= User.digest('Jsdfuisd8f') %>
activated: true
activated_at: <%= Time.zone.now %>
我是一个 Rails 菜鸟,所以它可能是一些基本的东西。提前致谢...
更新:请参阅下面与 kasperite 的讨论。我只需要添加on: create
到我的密码验证中。
调用update_attributes!
将触发save!
,进而触发对模型的验证。而且由于您不提供密码,它会抛出异常。
您可以执行update_attribute(:title, params[:title])
which 绕过验证或执行以下操作:
@user.title = params[:title]
@user.save!(validation: false)
请参阅:http : //api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update-21
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句