In a rails application, the following two validations are returning true
irb(main):017:0> User.new(nation_id: 1, email: 'test@mail.co', status_id: 3, sex_id: 1, password: '11111111', password_confirmation: '11111111' ).valid?
Nation Load (0.2ms) SELECT "nations".* FROM "nations" WHERE "nations"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
Categoryminor Load (0.2ms) SELECT "categoryminors".* FROM "categoryminors" WHERE "categoryminors"."id" = $1 LIMIT $2 [["id", 3], ["LIMIT", 1]]
Categoryminor Load (0.2ms) SELECT "categoryminors".* FROM "categoryminors" WHERE "categoryminors"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
User Exists? (0.4ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = $1 LIMIT $2 [["email", "test@mail.co"], ["LIMIT", 1]]
=> true
irb(main):018:0> User.new(nation_id: 1, mobile: '3331112200', status_id: 3, sex_id: 1, password: '11111111', password_confirmation: '11111111' ).valid?
Nation Load (0.4ms) SELECT "nations".* FROM "nations" WHERE "nations"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
Categoryminor Load (0.2ms) SELECT "categoryminors".* FROM "categoryminors" WHERE "categoryminors"."id" = $1 LIMIT $2 [["id", 3], ["LIMIT", 1]]
Categoryminor Load (0.1ms) SELECT "categoryminors".* FROM "categoryminors" WHERE "categoryminors"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
User Exists? (0.3ms) SELECT 1 AS one FROM "users" WHERE "users"."mobile" = $1 AND "users"."nation_id" = $2 LIMIT $3 [["mobile", 3331112200], ["nation_id", 1], ["LIMIT", 1]]
=> true
The model has the following validations defined
belongs_to :nation
belongs_to :status, class_name: 'Categoryminor'
belongs_to :sex, class_name: 'Categoryminor'
validate :at_least_one_identifier
validates :mobile, uniqueness: { scope: :nation_id, message: (I18n.t('user.define_one_mobile_per nation')) }, if: -> { mobile.present? }
validates :email, uniqueness: true, if: -> { email.present? }
def at_least_one_identifier
if [self.email, self.mobile].reject(&:blank?).size == 0
errors[:base] << (I18n.t('user.define_email_or_mobile'))
end
end
But the following first two tests Expected false to be truthy.
test "valid if email defined and mobile not defined" do
user = User.new(nation_id: 1, email: 'test@mail.co', status_id: 3, sex_id: 1, password: '11111111', password_confirmation: '11111111' )
assert user.valid?
end
test "valid if email undefined and mobile is defined" do
user = User.new(nation_id: 1, mobile: '3331112200', status_id: 3, sex_id: 1, password: '11111111', password_confirmation: '11111111' )
assert user.valid?
end
# the latter test fails as expected
test "invalid if email and mobile not defined" do
user = User.new(nation_id: 1, status: categoryminors(:active), sex: categoryminors(:male), password: '11111111', password_confirmation: '11111111' )
assert_not user.valid?
end
The data is identical; then what is wrong with the test ?
Aucun commentaire:
Enregistrer un commentaire