我正在阅读 railstutorial.org 上的最新 Rails 教程,我被困在某个练习上(http://ruby.railstutorial.org/chapters/updating-showing-and-deleting-users#sec:updating_deleting_exercises上的#8 )。您必须编写 rspec/capybara 测试以确保管理员无法自行删除。我有实现工作,但无法让测试正常工作。这是我的代码。我在这里发现了类似的问题:Ruby on Rails 语法和https://getsatisfaction.com/railstutorial/topics/how_to_prevent_admin_user_from_deleting_themselves。但我认为这是一个较旧的教程,而不是同一个问题。
以下是 spec/requests/user_pages_spec.rb 中的相关代码:
describe "User pages" do
subject { page }
describe "delete links" do
describe "as an admin user" do
let(:admin) { FactoryGirl.create(:admin) }
before do
sign_in admin
visit users_path
end
it "should not be able to delete themself" do
expect { admin.delete }.should_not change(User, :count)
end
end
end
end
end
错误消息说用户数减少了 1。
为了完整起见,这是我的(工作)实现:
class UsersController < ApplicationController
before_filter :current_admin, only: :destroy
def current_admin
@user = User.find(params[:id])
redirect_to users_path, notice: "Cannot delete current admin" if current_user?(@user)
end
end
我哪里错了,谢谢?(我遗漏了一些方法,但希望有足够的方法来弄清楚我想要做什么)
编辑:使用 Ruby v1.9.3,Rails v3.2.3。默认情况下,管理员没有删除链接。
Edit2:这是我的工作:
规格/控制器/users_controller_spec.rb
require 'spec_helper'
describe UsersController do
describe "admins" do
let(:admin) { FactoryGirl.create(:admin) }
it "should not be able to delete themself" do
sign_in admin
expect { delete :destroy, :id => admin.id }.should_not change(User, :count)
end
end
end
users_controller.rb
def destroy
@user = User.find(params[:id])
if current_user?(@user)
flash[:error] = "Cannot delete current admin"
else
@user.destroy
flash[:success] = "User destroyed."
end
redirect_to users_path
end