Skip to content

Instantly share code, notes, and snippets.

@shtakai
Created June 22, 2016 18:01
Show Gist options
  • Save shtakai/c8369643541fb14440bc659975f9373d to your computer and use it in GitHub Desktop.
Save shtakai/c8369643541fb14440bc659975f9373d to your computer and use it in GitHub Desktop.
Naïve and simpler User validations
class User < ActiveRecord::Base
attr_accessible :name, :password, :password_confirmation
has_secure_password
validates :password, presence: true, confirmation: true, length: { minimum: 8 }
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
has_secure_password
validates :password, length: { minimum: 8 }, allow_nil: true
end
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment