Railstutorial |第10章练习10.4.1.2 |为什么设置缩位密码?

问题描述 投票:1回答:1

练习说明: Railstutorial Exercise 10.4.1.2

练习: 'FILL_IN'必须替换为正确的代码,以便测试正常进行

test "should not allow the admin attribute to be edited via the web" do
  log_in_as(@other_user)
  assert_not @other_user.admin?
  patch user_path(@other_user), params: {
                                  user: { password:              FILL_IN,
                                          password_confirmation: FILL_IN,
                                          admin: FILL_IN} }
  assert_not @other_user.FILL_IN.admin?
end

我的解决方案:

test "should not allow the admin attribute to be edited via the web" do
  log_in_as(@other_user)
  assert_not @other_user.admin?
  patch user_path(@other_user), params: {
                                  user: { password:              'password',
                                          password_confirmation: 'password',
                                          admin: true } }
  assert_not @other_user.reload.admin?
end

我的问题:

如果已将':admin'属性设置为user_params(在UsersController类中)的允许参数列表中,则测试将按照预期的那样变为'红色'。我不明白的是,您可以设置随机密码,并且测试仍然可以正常进行,例如:

test "should not allow the admin attribute to be edited via the web" do
  log_in_as(@other_user)
  assert_not @other_user.admin?
  patch user_path(@other_user), params: {
                                  user: { password:              'foobar',
                                          password_confirmation: 'foobar',
                                          admin: true } }
  assert_not @other_user.reload.admin?
end

唯一有效的选项不是'password'(而不是'foobar'甚至不是”(即空白)),因为实例变量@other_user包含来自夹具文件'users'的User'archer'的值.yml”,谁将“ password”作为password_digest?会不会导致两个属性password_digest(='password')和password(='foobar')的不匹配?还是“弓箭手”的“ password_digest”属性也以某种方式更新了?如果是这样,它如何运作?

如果您输入无效的密码,测试为什么会变成“绿色”,如:

test "should not allow the admin attribute to be edited via the web" do
  log_in_as(@other_user)
  assert_not @other_user.admin?
  patch user_path(@other_user), params: {
                                  user: { password:              'foo',
                                          password_confirmation: 'bar',
                                          admin: true } }
  assert_not @other_user.reload.admin?
end

可能是由于错误的密码输入导致'patch'请求中止,因此也无法更新管理员状态?这是测试为什么是“绿色”的原因(因为管理员仍然是“零”)吗?

[我已经查找了Michael Hartl(https://bitbucket.org/railstutorial/sample_app_4th_ed)的示例应用程序的参考实现,但是很遗憾,他没有提供与练习有关的任何代码。

感谢您的帮助!

ruby-on-rails ruby railstutorial.org ruby-on-rails-5
1个回答
0
投票

在第10.1章中,对于更新测试,我们在用户控制器上允许使用空密码进行测试:

class User < ApplicationRecord
.
.
has_secure_password
validates :password, presence: true, length: { minimum: 6 }, allow_nil: true 
.
.
end

如同一章所述,已使用has_secure_password帮助程序保护了密码,以供在线使用。希望我有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.