Unit Test
Unit test for model, mainly in the test model business rules, test model validation validates rules.
Unit test files are stored in the Test/unit folder, and the unit test file for user model is USER_TEST.RB.
Common commands
The structure of the test database is synchronized from the DB/SCHEMA.RB.
After the database structure changes, you need to execute this command to keep the structure of the test database consistent with the latest database structure.
Rake Db:test:prepare
There are other related orders.
How to write and conduct unit tests
When you use the Rails G model user or Rails G scaffold user, you automatically create the model corresponding unit test file in the Test/unit folder.
Test/unit/user_test.rb
Require ' Test_helper '
class Usertest < activesupport::testcase
Test "email invalid" do
user = Users (: one
assert user.invalid?, "email invalid" End
test "email Invalid two" do
User=users (: two)
assert User.invalid?
End
test ' password do not match '
do user =users (: three)
assert user.invalid?
End
test ' All fields are valid ' do
user=user.new (:nickname=> "nickname",:email=> "Sdf@13123.xo",
:p assword=> "123456",
:p assword_confirmation=> "123456")
assert user.valid?
End
test ' password and password_confirmation do not match ' do
user = User.new (:nickname=> "asdf": email= > "Asdfasdf",:p assword=> "123",
:p assword_confirmation=> "234")
assert user.invalid?
End End
App/model/user.rb
Class User < ActiveRecord::Base
Attr_accessible:email,: Nickname,:p assword,:p assword_confirmation
attr_ Accessor:p assword,:p assword_confirmation
validates:p assword,: Confirmation => true
validates:p Assword_ Confirmation,:p resence => true
validates:email,:p resence => true,: Uniqueness => True,: Format => {: WI Th =>/^\w+@\w+\.\w+$/},
: Length => {: Maximum =>}
validates:nickname,:p resence => true,: Lengt H => {: In =>1..30} end
Test/fixtures/users.yml
One:
nickname:nickname1
email:invalidemail
two:
nickname:nickname2
Email: invalideamil@
Three:
nickname:nickname3
email:validemail@123.com
four:
nickname: Nickname4
email:validemail@baidu.com