RORGURU.COM
 

VALIDATING

 

What is the validation ?

While developing an online application, it is very necessary to check whether the user has filled up all necessary fields with proper data in an online form submission. Rails provides us some very easy ways to do this. Using validation we can easily check whether some fields or attributes for a specific model meet some particular conditions or criterion or not.


What we can do with validation ?

     We can check many things for a particular field of an attribute. Some of them are given below:

We can check whether the data is numerical or not.
We can check whether the desired field is unique or not.
We can fix the length of an attribute.

Validation Options :

You can use different validation options for different purposes. The options are:

: message => Shows an error message, default is can not be blank.
: if => specifies the symbol or method is true or false.
: on => default is: save and the other options are: update and: create.
: scope => is used to check the uniqueness.
: with => for regular expression.
: is, : minimum, : maximum => used for ranging.
: within => specifies the minimum and maximum size for an attribute.

Different Validate Methods :

TValidates uniqueness of : Validates that the attributes are unique in a table.

Example:

Class User < ActiveRecord :: Base

Validates_uniqueness_of :name

End:

Validates_presence_of : Validates that the field or attributes are not blank .

Example:

Class User < ActiveRecord :: Base

Validates_presence_of :age, :address

End:


IValidates_numericality_of : Validates that the attributes takes only numerical data.

Example:

Class User < ActiveRecord :: Base

Validates_numericality_of :age

End:

Validates_length_of : : Validates that the attributes maintain the specified length .

Example:

Class User < ActiveRecord :: Base

Validates_length_of :name, :within => 4..12

end:

Validates_confirmation_of : In web application sometimes we need two text fields like password field and the another one is confirm password field ,that times we need this validation .

Example:

class User < ActiveRecord :: Base

validates_confirmation_of :password

end:

Validates_format_of : Matches the specified format.

Example:

class User < ActiveRecord :: Base

validates_format_of :email_id, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i

end:

Validates_inclusion_of : Validates whether the data exists in a enumeration list .

Example:

class User < ActiveRecord :: Base

validates_inclusion_of :age ,:in =>5..50

end:

Validates_inclusion_of : Validates whether the data exists in a enumeration list .

Example:

class User < ActiveRecord :: Base

validates_inclusion_of :age ,:in =>5..50

end

validates_exclusion_of : Validates the data does not exists in a enumeration list .

Example:

class Book < ActiveRecord :: Base

validates_exclusion_of :price , :in =>20..25

end

validates_acceptance_of : Validates whether a checkbox has been checked

Example:

class User < ActiveRecord :: Base

validates_acceptance_of :box

end


TESTING


In Rails when you create an application, the Rails framework automatically create a test directory for that application. In Rails there are three testing methods.

Unit Tests - The unit test is used for model testing
MFunctional Tests - The controller of a Rails application is tested under the functional test.
Integration Tests The integration test is the new feature of Rails framework.

Unit Testing : To test a model first we need ,

To create a model
Create the development database and test database [db:create:all]
Migrate the database [db:migrate]
Then run db:test:clone ,it recreates the test database from the current environment database schema .

When we create a model a corresponding test file, with the name like model-name_test.rb, is generated in the unit test directory.

For example, if the model name is Book, then the test file name will be book_test.rb.

The general form of a test will be-

require File.dirname(_FILE_) + `/../test_helper`

class Book_test < Test : : Unit : :TestCase

fixtures :books

def test_truth

assert true

end

end

In Unit tests, there are three in-built methods,

Setup - Setup is the first method that executes before any tests are executed. We can use it for initialization.
Teardown - It can be used for cleanup.
Tests truth It is a method .You can replace it with your own test method or you can keep it.

Some important rules :

In any test, we have to write the method name like this ,

Syntax :

def test_method-name

......

end

Example :

def test_calculation

code

end

In test, the methods are executed in alphabetical order.

Example:

Suppose you have two test methods:

def test_calculation

code

end

def test_priÎ

code

end

The calculation method will be executed first then the price method will be executed.

In a method, if the first assert statement is false then the first one is executed but the other statements are not executed .

Example :

ddef test_total

assert (2 + 1= = 5, False )

assert (2 + 2= = 5, True )

end

Output : False
In test, the methods are executed in alphabetical order.

Example :

Using assert statement and assert_equal statement :

Assert : Assert statement just check the condition is true or false . If it is false then it returns the message .
Example :

require File.dirname(_FILE_) + `/../test_helper` class Book_test < Test : : Unit : :TestCase def test_message assert (5 + 2 = =6 , The result is false) end end

Output : The result is false

Assert_equal : It takes three arguments .First one is expected value , second one is the actual value and the third argument is a message .If the expexted value and actual value is not same or becomes false then the message will be shown .

Example :

require File.dirname(_FILE_) + `/../test_helper`

class User_test < Test : : Unit : :TestCase def test_show

assert (5 + 2 = =6 , The result is false)

end

end

Output : Result mismatch

Suppose you have two test methods:

def test_calculation

code

end

def test_priÎ

code

end

The calculation method will be executed first then the price method will be executed.

In a method, if the first assert statement is false then the first one is executed but the other statements are not executed .

Example :

ddef test_total

assert (2 + 1= = 5, False )

assert (2 + 2= = 5, True )

end

Output : False

In test, the methods are executed in alphabetical order.

Example :

Testing the two models :

Suppose there are two models Employee and Project .

Attributes of employees table: - employee_name, designation, age, gross_salary, deduction, net_salary

Attributes of projects table: - project_name, start_date, completion_date, rate, total_cost .

We shall prepare one-to-one and one-to-many association for employees and projects table.

We shall define the following actions for Employee class age_calculation(),

salary_calculation() [net_salary = gross_salary - deduction]

3) Preapare test cases for these three methods. You will have to write test cases for both kinds of associations

4) Define following actions for Project class project_duration() [completion date - start date]

5) Preapare test cases for this methods. You will also have to write test cases for both kinds of associations.

FOR ONE_TO_ONE ASSOCIATION :

Code for employee model :

class Employee < ActiveRecord::Base

has_one :project

def age_calculation()

Time.now.year - dob

end

def show_employee_name_designation()

@show_employee_name_designation ||= [employee_name,designation]

end

def salary_calculation()

gross_salary - deduction

end

end

Code for project model :

class Project < ActiveRecord::Base

belongs_to :employee


def project_duration()

# @project = project.find(1)

@completion_date = completion_date

@start_date = start_date

@completion_date =

@completion_date.strftime("%Y")

@start_date =

@start_date.strftime("%Y")

@completion_date =

@completion_date.to_i

@start_date = @start_date.to_i

@completion_date - @start_date

end

end

Code for employees.yml :

employee:

id: 1

employee_name: ram

designation: consultant

dob: 1984

gross_salary: 435

deduction: 43

net_salary: 656

Code for projects.yml :

tlclostpets:

id: 1

employee_id: 1

project_name: projk

start_date: 2008-12-27

completion_date: 2005-12-27

rate: 4

total_cost: 245

Code for employee_test.rb

require File.dirname(__FILE__) +

'/../test_helper'

class EmployeeTest <

ActiveSupport::TestCase

fixtures :employees,:projects

# Replace this with your real tests.

def test_truth

assert true

end

def setup

@employee = employees(:employee)

@tlclostpets = projects(:tlclostpets)

# @employee.project = [@tlclostpets]

end

def test_relationship

assert_equal(1, @employee.id,"match")

assert_equal(1,

@employee.project.employee_id,"match")

assert_equal("projk",

@employee.project.project_name,"match")

end

def test_age_calculation

assert_equal(50,@employee.age_calculation,"mismatch")

end

def test_show_employee_name_designation

assert_equal(['ram','consultant'],@employee.show_employee_name_designation(),"match" )

end

def test_salary_calculation()

assert_equal(23,@employee.salary_calculation(),"mismatch")

end

end

Output for employee_test.rb



Code for projects_test.rb :

require File.dirname(__FILE__) +

'/../test_helper'

class ProjectTest <

ActiveSupport::TestCase

# Replace this with your real tests.

fixtures :employees,:projects

def setup

@employee = employees(:employee)

@tlclostpets = projects(:tlclostpets)

end

def test_relationship

assert_equal(1,@employee.project.employee_id)

assert_equal(1,

@tlclostpets.employee.id,"mismatch")

assert_equal('ram',

@tlclostpets.employee.employee_name)

end


def test_truth

assert true

end


def test_project_duration

assert_equal(3,

@tlclostpets.project_duration(),"mismatch")

end

end

Output for projects_test.rb :



FOR ONE_TO_MANY ASSOCIATION :

Code for employee model :

class Employee < ActiveRecord::Base

has_many :projects


def age_calculation()

Time.now.year - dob

end

def salary_calculation()

gross_salary - deduction

end

def show_employee_name_designation()

@show_employee_name_designation ||=

[employee_name,designation]

end

end


Code for project model :

class Project < ActiveRecord::Base

belongs_to :employee


def self.project_duration()

@project = Project.find(1)

@completion_date = @project.completion_date

@start_date = @project.start_date

@completion_date =

@completion_date.strftime('%d')

@start_date = @start_date.strftime('%d')

@completion_date = @completion_date.to_i

@start_date = @start_date.to_i

@completion_date - @start_date

end

end


Code for employees.yml :

employee:

id: 1

employee_name: ram

designation: consultant

dob: 1980

gross_salary: 435

deduction: 43

net_salary: 656


Code for projects.yml

tlclostpets:

id: 1

project_name: projk

start_date: 2008-12-27

completion_date: 2005-12-27

rate: 4

total_cost: 245


execusoft:

id: 2

project_name: balco

start_date: 2008-12-27

completion_date: 2005-12-27

rate: 6

total_cost: 24556

Code for employee_test :

require File.dirname(__FILE__) +

'/../test_helper'

class EmployeeTest < ActiveSupport::TestCase

fixtures :employees, :projects

# Replace this with your real tests.

def setup

@employee = employees(:employee)

@tlclostpets = projects(:tlclostpets)

@execusoft= projects(:execusoft)

@employee.projects = [@tlclostpets,

@execusoft]

end


def test_relation

assert_equal(1, @employee.id)

# showing employee_id undefined

assert_equal(2, @employee.projects.count, "mismatch")

end


def test_age_calculation

# @employee = Employee.new(:dob=>'1980')

assert_equal(50, @employee.age_calculation(),"false")

end


def test_truth

assert true

end


def test_show_employee_name_designation

assert_equal(['ram','doc'],

@employee.show_employee_name_designation,"doesnot ")

# assert_equal('consultant',@employee. designation,"wrong")

end


def test_salary_calculation

assert_equal('52',@employee.salary_calculation,"doesnt match")

end

end


Output for employee_test.rb


Code for project_test.rb :

require File.dirname(__FILE__) +
'/../test_helper'
class ProjectTest < ActiveSupport::TestCase
fixtures :employees, :projects
# Replace this with your real tests
def setup
@employee = employees(:employee)
@tlclostpets = projects(:tlclostpets)
@execusoft = projects(:execusoft)
@employee.projects = [@tlclostpets,
@execusoft]
end


def test_calculation
aassert_equal(2, @employee.projects.count)
assert_equal("string reverse",@employee.projects.sort_by{|w|w.project_name}.first.project_name)
end


def test_truth
assert true
end
def test_project_duration


assert_equal(12,@employee.projects.project_duration(),"x")
end
end


Output for project_test.rb