У меня возникли проблемы с разработкой и подтверждением пароля. Я создал тест модели в rails4, который выглядит следующим образом:Проверка правильности определения пароля и пароля
test "user requires a password_confirmation" do
user = FactoryGirl.build(:user)
assert user.valid?, "FactoryGirl should return a valid user"
user.password_confirmation = nil
# These are just some outputs to verify what's going on.
# This is the condition in devises's password_required? method
puts !user.persisted? || !user.password.nil? || !user.password_confirmation.nil? #=> true
puts user.valid? #=> true
assert user.invalid?, "Password confirmation should be required" # Fails here
assert_equal 1, user.errors.size, "Only one error should have occured. #{user.errors.full_messages}"
end
Этот тест не на втором утверждают ("Password confirmation should be required"
).
Вот моя полная модель Пользователь:
class User < ActiveRecord::Base
has_one :user_entity
has_one :manager,through: :user_entity, source: :entity, source_type: 'Manager'
has_one :client, through: :user_entity, source: :entity, source_type: 'Client'
# Adds default behavior. See: https://github.com/stanislaw/simple_roles#many-strategy
simple_roles
validates :username,
presence: true,
length: { minimum: 4, allow_blank: true, if: :username_changed? },
uniqueness: { allow_blank: true, if: :username_changed? },
format: { with: /\A[A-z_0-9]+\z/, allow_blank: true, if: :username_changed? }
# Include default devise modules. Others available are:
# :token_authenticatable, :timeoutable, :omniauthable, :registerable
devise :database_authenticatable, :recoverable, :rememberable,
:trackable, :validatable, :confirmable, :lockable
# Virtual attribute for authenticating by either username or email
# This is in addition to a real persisted field like 'username'
attr_accessor :login
def self.find_first_by_auth_conditions(warden_conditions)
conditions = warden_conditions.dup
# User need to be active
conditions[:active] = true
if login = conditions.delete(:login)
where(conditions).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
else
where(conditions).first
end
end
def entity
self.user_entity.try(:entity)
end
def entity=(newEntity)
self.build_user_entity(entity: newEntity)
end
end
Я пытался добавить в моей модели пользователя:
validates :password, confirmation: true
После этого тест пройден, но я получаю сообщение об ошибке на следующем:
1) Failure:
UserTest#test_user_requires_a_password [/my/project/test/models/user_test.rb:52]:
Two errors should have occured. ["Password confirmation doesn't match confirmation", "Password confirmation doesn't match confirmation", "Password can't be blank"].
Expected: 2
Actual: 3
Как вы можете видеть, это похоже на то, что проверка подтверждения происходит два раза и не выполняется оба раза.
Я использую rails4 (край) и ветку rails4 для разработки.
EDIT: Я попытался установить
user.password_confirmation = "#{user.password}_diff"
И тест пройден. Итак, почему подтверждение игнорируется при установке nil
? Поскольку объект еще не сохранен, я бы предположил, что подтверждение пароля должно быть предоставлено.