我User
在 Ruby on Rails 中有这个类:
class User < ActiveRecord::Base
after_destroy :ensure_an_admin_remains
private
def ensure_an_admin_remains
if User.where("admin = ?", true).count.zero?
raise "Can't delete Admin."
end
end
end
如果有人不小心删除了管理员用户,这很有效,并且会导致数据库回滚。
问题是它似乎破坏了用户删除操作,即使在使用非管理员用户(由 Factory Girl 生成)进行测试时也是如此。这是我的user_controller_spec.rb
:
describe 'DELETE #destroy' do
before :each do
@user = create(:non_admin_user)
sign_in(@user)
end
it "deletes the user" do
expect{
delete :destroy, id: @user
}.to change(User, :count).by(-1)
end
end
每当我运行此测试时,都会收到此错误:
Failure/Error: expect{
count should have been changed by -1, but was changed by 0
不过,不应该有任何错误,因为@user
默认情况下 ' 的 admin 属性设置为 false 。
有人可以帮我吗?
谢谢...