require "digest/sha2"
class User < ActiveRecord::Base
attr_accessible :name,:password,:password_confirmation
validates :name,:presence =>true,:uniqueness => true
validates :password,:confirmation =>true
attr_accessor :password_confirmation
attr_reader :password
validate :password_must_be_present
def password=(password)
@password = password
if password.present?
generate_salt
self.hashed_password = self.class.encrypt_password(password,salt)
end
end
def User.authenticate(name,password)
if user == find_by_name(name)
if user.hashed_password == encrypt_password(password,user.salt)
user
end
end
end
private
def password_must_be_present
errors.add(:password,"密码错误")unless hashed_password.present?
end
def User.encrypt_password(password,salt)
Digest::SHA2.hexdigest(password + "wibble" + salt)
end
def generate_salt
self.salt= self.object_id.to_s + rand.to_s
end
end
describe User do
it "正确参数" do
user = FactoryGirl.build(:user1)
assert user.valid?
end
it "name值为空时,user对象应该无效" do
user = FactoryGirl.build(:user2)
assert user.invalid?
end
it "password虚拟属性为空时,user对象应该无效" do
user = Factory.build(:user5)
user.should_not be_valid
user.should have(1).errors_on(:password)
end
it "password_confirmation虚拟属性为nil时,user对象应该无效" do
user = Factory.build(:user_password_confirmation_nil)
assert user.invalid?
user.should have(1).errors_on(:password)
end
it "两次密码不相同时,user对象应该无效" do
user = FactoryGirl.build(:user3)
assert user.invalid?
end
it "当name已经存在时,对象不应该被创建并会报关于:name的错误" do
fist_user = Factory.create(:user1) #factory用create创建表示还有save动作而用 build则没有save
user = Factory.build(:user1)
assert user.invalid?
user.should have(1).errors_on(:name) #结果会有关于name一个错误。
end
end
FactoryGirl.define do
factory :user1 ,:class =>:User do
name "user1"
hashed_password "MyString"
salt "MyString"
password "123"
password_confirmation "123"
end
factory :user2 ,:class =>:User do
name ""
hashed_password "MyString"
salt "MyString"
password "123"
password_confirmation "123"
end
factory :user3 ,:class =>:User do
name "user3"
hashed_password "MyString"
salt "MyString"
password "123"
password_confirmation "1234"
end
factory :user4 ,:class =>:User do
name "user4"
hashed_password "MyString"
salt "MyString"
end
factory :user5 ,:class =>:User do
name "user1"
password ""
password_confirmation ""
end
factory :user_password_confirmation_nil ,:class =>:User do
name"user"
password "123456"
password_confirmation ""
end
end
需要注意的是 password_confirmation和 password是虚拟属性,在测试数据时要注意排除hashed_password salt属性的干扰。