shtakai
6/22/2016 - 6:01 PM

Naïve and simpler User validations

Naïve and simpler User validations

require 'spec_helper'

describe User do
  describe "Validations" do
    context "on a new user" do
      it "should not be valid without a password" do
        user = User.new password: nil, password_confirmation: nil
        user.should_not be_valid
      end

      it "should be not be valid with a short password" do
        user = User.new password: 'short', password_confirmation: 'short'
        user.should_not be_valid
      end

      it "should not be valid with a confirmation mismatch" do
        user = User.new password: 'short', password_confirmation: 'long'
        user.should_not be_valid
      end
    end

    context "on an existing user" do
      let(:user) do
        u = User.create password: 'password', password_confirmation: 'password'
        User.find u.id
      end

      it "should be valid with no changes" do
        user.should be_valid
      end

      it "should not be valid with an empty password" do
        user.password = user.password_confirmation = ""
        user.should_not be_valid
      end

      it "should be valid with a new (valid) password" do
        user.password = user.password_confirmation = "new password"
        user.should be_valid
      end
    end
  end
end
class User < ActiveRecord::Base
  has_secure_password
  
  validates :password, length: { minimum: 8 }, allow_nil: true
end
Failures:

  1) User Validations on an existing user should be valid with no changes
     Failure/Error: user.should be_valid
       expected #<User id: 1, name: nil, password_digest: "$2a$10$RHM/cgdPBD7Qm0Xemy07eeS.8wCcoYiXZDGMfRMEPhwS...", created_at: "2013-08-05 20:49:22", updated_at: "2013-08-05 20:49:22"> to be valid, but got errors: Password can't be blank, Password is too short (minimum is 8 characters)
     # ./spec/models/user_spec.rb:29:in `block (4 levels) in <top (required)>'
class User < ActiveRecord::Base
  attr_accessible :name, :password, :password_confirmation
  has_secure_password

  validates :password, presence: true, confirmation: true, length: { minimum: 8 }
end