我Ruby on Rails中這個User
類:如何在Rails和RSpec中測試after_destroy回調?
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
的管理屬性設置爲false默認。
有人可以幫我嗎?
謝謝...
應該是驗證 – apneadiving 2013-03-03 15:04:54