1. rake db:reset
this command is very useful, it will clear the old sample data from database, so we again have a clean database
2. here, we will just use plain password, with bad secure, we will talk about password security later.
3. again, we will start from test!!!!
now in the sample data in the spec test, should change to:
before(:each) do
@attr = {
:name => "sb",
:email => "sb@sb.com",
:password => "123456",
:password_confirmation => "123456"
}
end
below are some password validation test:
describe "password validation" do
it "should require a password" do
User.new(@attr.merge(:password=>"", :password_confirmation => "")).should_not be valid
end
end
4. We won't add a password attribute to the database, instead, we will store a encrypted_password attribute, so for the password, we will introduce a virtual attribute, which is an attr that not corresponding to a colume in the database.
the way to define a virtual attribute is to use attr_accessor method.
this attribute will not be written into database, will only exist in memory.
for the password_confirmation, we even will not have a virtual attribute for it, instead, it is used in the validation:
validates :password, :confirmation => true
this line will auto create a virtual attribute called "password_confirmation", and confirm it matches the password attribute.
attr_accessor :password (this line is to create a virtual attribute)
attr_accessible :name, :email, :password, :password_confirmation
the second line is used to prevent mass assignment vulnerability.
5. next we will add a column into users table.
a way to test if a model respond to a method:
user = User.new
user.respond_to? :password
user.respond_to? :encrypted_password
rails g migration add_password_to users encrypted_password:string
the "_to_users" make rails automatically construct a migration to add columns to the users table. and by including the 2nd argument, we give Rails enough info to construct the entire migration for us.
ok, next,
rake db:migrate
rake db:test:prepare