gpt4 book ai didi

ruby-on-rails - railstutorial.org,第 9 章练习,9

转载 作者:行者123 更新时间:2023-12-02 22:14:00 25 4
gpt4 key购买 nike

这个想法是为了让管理员用户无法 self 毁灭。我写了以下测试:

describe "as admin user" do
let(:admin) { FactoryGirl.create(:admin) }
before { valid_signin admin }

describe "should not be able to delete himself by submitting a DELETE request to the Users#destroy action" do
specify do
expect { delete user_path(admin) }.not_to change(User, :count).by(-1)
end
end
end

并因此修改了销毁操作:

def destroy
@user = User.find(params[:id])
unless current_user?(@user)
User.find(params[:id]).destroy
flash[:success] = "User destroyed."
redirect_to users_url
end
end

(如果您是管理员用户,您只能访问销毁操作)。

测试现在应该通过了,但实际上没有。我收到以下错误消息:

Failure/Error: expect { delete user_path(admin) }.not_to change(User, :count).by(-1)
ActionView::MissingTemplate:
Missing template users/destroy, application/destroy with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :coffee]}.

我不明白缺少模板的错误信息,也不明白为什么测试没有通过。

最佳答案

尝试将您的 destroy 操作更改为类似这样的内容,看看您的测试是否通过:

def destroy
user = User.find(params[:id])
unless current_user?(user)
user.destroy
flash[:success] = "User destroyed."
else
flash[:error] = "You can't destroy yourself."
end
redirect_to users_url
end

我认为问题在于,如果您成功销毁用户,您只会重定向到 users_url。如果你不这样做(即管理员试图 self 毁灭),那么就没有重定向,Rails 将开始寻找一个名为 destroy.html.erb 的 View ,但在任何地方都找不到,并且引发异常。这也是方法中的 user 变量从 @user 更改为 user 的原因:局部变量将代替实例变量,因为它不需要使用在 View 中。

如果这不是问题所在,请编辑您的问题,将您当前代码包含到 Github 存储库的链接。

关于ruby-on-rails - railstutorial.org,第 9 章练习,9,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14794181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com