Add destroy_with_password method

This commit is contained in:
Michiel Prins 2013-04-29 15:06:13 +02:00
parent dceb788c6b
commit 60e933df73
2 changed files with 42 additions and 0 deletions

View File

@ -95,6 +95,22 @@ module Devise
result
end
# Destroy record when :current_password matches, otherwise returns
# error on :current_password. It also automatically rejects
# :current_password if it is blank.
def destroy_with_password(current_password)
result = if valid_password?(current_password)
destroy
else
self.valid?
self.errors.add(:current_password, current_password.blank? ? :blank : :invalid)
false
end
self.current_password = nil
result
end
def after_database_authentication
end

View File

@ -183,6 +183,32 @@ class DatabaseAuthenticatableTest < ActiveSupport::TestCase
assert user.valid_password?('12345678')
end
test 'should destroy user if current password is valid' do
user = create_user
assert user.destroy_with_password('12345678')
assert_raise ActiveRecord::RecordNotFound do
user.reload
end
end
test 'should not destroy user with invalid password' do
user = create_user
assert_not user.destroy_with_password('other')
assert_nothing_raised ActiveRecord::RecordNotFound do
user.reload
end
assert_match "is invalid", user.errors[:current_password].join
end
test 'should not destroy user with blank password' do
user = create_user
assert_not user.destroy_with_password(nil)
assert_nothing_raised ActiveRecord::RecordNotFound do
user.reload
end
assert_match "can't be blank", user.errors[:current_password].join
end
test 'downcase_keys with validation' do
user = User.create(:email => "HEllO@example.com", :password => "123456")
user = User.create(:email => "HEllO@example.com", :password => "123456")