`
peryt
  • 浏览: 55302 次
  • 来自: ...
最近访客 更多访客>>
社区版块
存档分类
最新评论
  • waiting: 既然都指定了dataType为'script'那就不必特别在b ...
    jQuery

6.2 user validations

阅读更多

1. ok, let's add validations to our models:

a. name should not be blank.

b. email should follow email format.

c. email should be unique.

 

2. there are some common validations:

validates pressences, length, unique, format, and add confirmation.

 

3. we will continue to use test-driven dev.

 

since we are going to test, we need to copy the dev database structure are copied over to test database:

 

rake db:test:prepare

 

this command will copied the structure in db/development.sqlite3 to db/test.sqlite3

 

4. sometimes, you are not clear about what to test during TDD, at this time, you can dev first, then, after it is clear, comment out the dev code, write a failing test, then uncomment your dev code, see if the test pass.

 

This comment-write_test-uncomment, work flow will also work if you want to write test to code writen by another guy.

 

5. Validates the pressence of a attribute:

 

validates :name, :pressence => true

 

note: :pressence => true, is a hash, remember, if the last argument is a hash, the braces can be omitted.

 

attr_accessible,

valiates

are both just methods, 

 

6. let's see if our validates are working?

 

user = User.new(:name => "", :email => "jfjdsl@jdlj.com")

user.save

=> false

user.valid?

=> false

 

user.valid?  this method will check all validations, if one fails, will return false.

 

when checking the pressence of a field, rails is using this method:

 

object.blank? 

 

so an empty string will fail the pressence validation.

 

7. the validations will generate a errors object.

 

user.errors.full_messages

 

this will return an array of all error messages from validations.

 

=> ["Name can't be blank"]

 

8. ok, let's comment out the validate, then write a failing test:

 

 

we will use rspec:

 

 

describe User do
  before(:each) do
    @attr = {:name = "fjdlfds",  :email => "ajflds@fjldsjf.com"}
  end
  
  it "should create a valid user" do
    User.create!(@attr)
  end

  it "should have a user name"

end

 ok, let's anlyze this part of code:

 

a. before(:each) is saying, before each spec run, this part of code must be executed first.

b. User.create!(@attr),  read as "create bang", this will throw a exception if the create failed!!

c. it "should have a user name", this is without do .... end,  rspec will know this is a pending.

 

9, next, we will try to fill in the pending test.

we need to hash with a blank user name.

to do this, we can use the merge method of hash class:

 

*merge method is an important method of hash class*

 

this will add new key-value pair to a hash, if this key already exist, the new value will replace old one.

 

it "should require a name" do
    no_name_user = User.new(@attr.merge(:name => ""))
    no_name_user.should_not be_valid
  end
 

looking at this code, merge method is doing its job.

 

and should_not is a method of rspec.

 

be_valid is a little tricky, this model is responding to the valid? method, so rspec will automatically have be_valid method.

 

so if a model has a fdsfdsds? method, then the rspec will auto have a be_fdsfdsds method

 

 

10. next, let's add some validation to the length of the name field:

 

also, first, let's write a failing test:

 

 

it "should reject names that are too long" do
    long_name = "a" * 51
    long_name_user = User.new(@attr.merge(:name => long_name))
    long_name_user.should_not be_valid
end

 

then, let's add a line of code to user.rb to make the test pass

 

validates :name, :presence => true, :length => {:maximum => 50}

 

("a" * 51 = "aaaaaaaaaaaaaaaa.......")

 

 

11. the next validation is email format validation

 

we can't say we have a perfect validation, but we should try to allow most valid email format, and forbid most invalid format.

 

again, we start from test, we first should have a collection of valid and invalid email format, for convenience, we first introduce a useful way to define a string array:

 

%w[foo bar baz]

 

addresses = %w[chad@chad.com THE_USER@foo.bar.org first.last@foo.jp]

 

 

we need to use regular expression (regex) in ruby to verify the email format.

 

email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

 

to understand this regex, you can refer to www.rubular.com, or check against the Table 6.1 in rubyonrails tutorial book.

 

 

12. next, let's add a uniqueness check on email address:

again, start from test.

 

a. we need a existing user record, so we will use:

 

User.create!(@attr)

 

we use create! because if it fails, it will throw an exception, so that we know it fails.

or, we won't observe it fails, that will cause trouble.

 

b. the validation code in the model will be:

 

validates :email, :presence => true, :format => {:with => email_regex}, :uniqueness => true

 

 

c. we are not done yet, we haven't consider the case-insensitive issue, so the test code should be:

 

it "should reject email addresses identical up to case" do

  upcased_email = @attr[:email].upcase

  User.create!(@attr.merge(:email => upcased_email))

  user_with_dup_email = User.new(@attr)

  user_with_dup_email.should_not be_valid

end

 

and the validation code in the model will be:

 

validates :email, :presence => true, :format => {:with => email_regex}, 

:uniqueness => {:case_sensitive => false}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

ok, we are done, congrats, we follow the TDD principle!!

 

 

 

 

分享到:
评论

相关推荐

    ember-validations:Ember-Validations - 用于处理对象验证的 Ember.js 库

    Ember 验证 警告:此项目不再更新。 是一个很棒的类似库Ember-validations 是一个 Ember.js 库,可以... User = Ember . Object . extend ( Ember . Validations , { country : null , validations : { name : { presen

    ember-i18n-cp-validations:ember-i18n支持ember-cp-validations

    ember-i18n-cp-validations 在ember-cp-validations中增加了对ember-i18n的支持 使用ember-intl? 请参阅: 安装 ember install ember-i18n-cp-validations 在ember-i18n-cp-validations中在2.x和3.x之间进行重大...

    meteor-validations:流星变量验证的基础

    验证方式流星变量验证的基础安装meteor add zhaoyao91:validations 介绍该软件包定义了验证类,一个简单的架构,一些帮助根据架构构建验证树的函数以及一组内置验证。验证类别这是编写新的验证类的模板: /** * the ...

    Python库 | cuenca_validations-0.9.17.dev20.tar.gz

    《Python库cuenca_validations详解》 在Python的生态系统中,库扮演着至关重要的角色,它们提供了丰富的功能,使得开发者能够高效地构建各种应用程序。本文将深入探讨名为`cuenca_validations`的Python库,它在...

    Python库 | db_validations-0.1.1.tar.gz

    《Python数据库验证库db_validations详解》 在Python编程领域,数据库操作是后端开发中的重要环节,确保数据的有效性和一致性至关重要。db_validations库,正如其名,专注于提供数据库验证功能,帮助开发者构建更加...

    Python库 | cuenca_validations-0.9.8.dev1.tar.gz

    《Python库cuenca_validations详解》 在Python的生态系统中,库扮演着至关重要的角色,它们提供了丰富的功能,使得开发者能够高效地构建各种应用程序。本文将深入探讨一个名为`cuenca_validations`的Python库,该库...

    cp-validations:ember-intl对ember-cp-validations的支持

    @ ember-intl / cp-validations 在ember-cp-validations中增加了对支持 使用ember-i18n? 请参阅: 要求 > = 2.0.0-rc.5 ember-cp-validations > = 2 安装 ember install @ember-intl/cp-validations 配置中 在...

    Python库 | validations-libs-1.0.4.tar.gz

    标题中的"Python库 | validations-libs-1.0.4.tar.gz"表明这是一个与Python相关的库,名为"validations-libs",版本号为1.0.4,且已打包成tar.gz格式的压缩文件。在Python编程中,库(Library)是预先编写好的代码...

    Python库 | cuenca_validations-0.9.17.dev6.tar.gz

    《Python库cuenca_validations详解》 在Python的开发世界中,库是开发者们的重要工具,它们提供了丰富的功能,让编程工作变得更加高效。本文将深入探讨名为`cuenca_validations`的Python库,该库是版本0.9.17.dev6...

    PyPI 官网下载 | cuenca_validations-0.9.10.dev4.tar.gz

    《PyPI官网下载:cuenca_validations-0.9.10.dev4.tar.gz——深入解析Python库的构建与发布》 PyPI(Python Package Index),是Python开发者的重要资源库,它为全球的Python爱好者提供了无数开源软件包和模块,...

    PyPI 官网下载 | tripleo_validations-8.4.2-py2-none-any.whl

    《PyPI官网下载:tripleo_validations-8.4.2-py2-none-any.whl》 在Python的世界里,PyPI(Python Package Index)是最重要的软件仓库,它为开发者提供了一个平台来发布和分享他们的Python软件包。标题中的"PyPI ...

    PyPI 官网下载 | cuenca_validations-0.9.0.0rc0.tar.gz

    《PyPI官网下载:cuenca_validations-0.9.0.0rc0.tar.gz——探索Python库在分布式环境中的应用》 PyPI(Python Package Index)是Python社区广泛使用的软件包仓库,它提供了丰富的Python库供开发者下载和使用。在...

    Python库 | cuenca_validations-0.6.7.dev4-py3-none-any.whl

    **Python库:cuenca_validations** `cuenca_validations`是一个专为Python开发者设计的库,主要用于处理与Cuenca API交互时的数据验证。Cuenca是一个金融技术平台,提供API接口来处理支付、转账等金融业务。`cuenca...

    PyPI 官网下载 | cuenca_validations-0.7.7.dev1.tar.gz

    《PyPI官网下载:cuenca_validations-0.7.7.dev1.tar.gz——深入理解Python库的构建与发布》 在Python的世界里,PyPI(Python Package Index)是官方的软件仓库,它为开发者提供了发布和分享自己创建的Python库的...

    validations:Validations 是一个 GORM 扩展,用于在创建、更新时验证模型

    验证 验证提供了一种在创建和更新模型时模型的方法。 ... import ( ... "github.com/qor/validations" ) func main () { db , err := gorm .... validations ....func ( user User ) Validate ( db * gorm. DB )

    Laravel开发-laravel-extended-validations

    Laravel的内置验证规则已经相当丰富,但有时我们可能会遇到一些特定的需求,这时"Laravel开发-laravel-extended-validations"包就派上用场了。这个开源包是为了扩展Laravel的默认验证功能,提供更多的验证规则,以...

    Android代码-Android-EditText-Validations

    Android EditText Validations Easily Validate EditTexts This library is best used with Kotlin, and is to help reduce boilerplate code when writing validation rules for EditText fields. To install: ...

    Laravel开发-laravel-validations

    本教程将深入探讨`laravel-validations`,这是Laravel中的验证机制,它提供了一种优雅的方式来处理输入数据的验证。 **一、验证基础** 1. **验证控制器方法**:在控制器中,我们通常会在处理用户请求的方法内进行...

    Angular-ionic-forms-and-validations.zip

    Angular-ionic-forms-and-validations.zip,使用这个Ionic示例应用程序学习如何处理Ionic 3和Angular 4中的表单和验证。在这个精彩的教程中,我们将介绍简单的和自定义的验证,并教您如何处理错误消息。,Angularjs于...

    database_validations:ActiveRecord的数据库验证

    安装将此行添加到您的应用程序的Gemfile中: gem 'database_validations' 然后执行: bundle 或将其自己安装为: gem install database_validations 查看应用程序以了解详细信息。基准() 图片,您将User模型定义为...

Global site tag (gtag.js) - Google Analytics