我已经开始学习Rails了,我第9章第三次练习了。
练习如下所示:
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 :update, id: @other_user, user: { password: FILL_IN,
password_confirmation: FILL_IN,
admin: FILL_IN }
assert_not @other_user.FILL_IN.admin?
end
我的问题是last Fill_IN >> assert_not @other_user.FILL_IN.admin
?
@other_user
取自Fixture,如下所示:
archer:
name: Sterling Archer
email: duchess@example.gov
password_digest: <%= User.digest('password') %>
Update action
看起来像这样:
def update
@user = User.find(params[:id])
if @user.update_attributes(user_params)
flash[:success] = "Profile updated"
redirect_to @user
else
render 'edit'
end
end
我还将:admin
添加到了user_params中,以便:admin param
可以修改:
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation, :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 :update, id: @other_user, user: { password: @other_user.password,
password_confirmation: @other_user.password_confirmation,
admin: true }
assert_not @other_user.admin?
end
但看起来@other_user没有被修改,所以我认为错误是最后一个断言。
我的回答是错的,我无法让这个测试失败,这是因为在最后的断言中"assert_not @other_user.FILL_IN.admin?"
我不知道在FILL_IN部分放什么。我试图切断FILL_IN,但这不起作用。
答案 0 :(得分:22)
您必须在更改基础记录后重新加载实例变量。这将加载新的更改。
assert_not @other_user.reload.admin?
答案 1 :(得分:5)
如今,在本教程的第4版中,使用Rails 5.0.0,我的答案是:
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_confirmation: "",
admin: true } }
assert_not @other_user.reload.admin?
end
密码和密码_确认字段可以留空,imho;如另一个例子清单10.11所示(在Rails 5版本中)。
答案 2 :(得分:0)
关于你的代码还有一件事 - 我也正在研究Hartl教程,我想如果PATCH
请求中的密码设置为@other_user.password
(以及密码)确认),即使:user
中允许user_params
,您的测试也会变为绿色,此时测试实际上应为红色。
这是因为:archer
灯具文件中的users.yml
没有:password
属性;他只有password_digest: <%= User.digest('password') %>
,你不能在密码被哈希后解除密码,就像他的密码一样。
只需将条目更改为
即可{ password: 'password', password_confirmation: 'password' ... }
并且测试应该测试正确的事情。
答案 3 :(得分:0)
我遇到了与您相同的问题,根据上述帮助,这应该是正确的答案:
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