Welcome

首页 / 软件开发 / 数据结构与算法 / Rails测试《十》不能错过的杂七杂八

Rails测试《十》不能错过的杂七杂八2014-03-15今天来介绍一些杂七杂八的测试知识,但是它们是不能错过的。

首先来介绍一下常用的测试命令

rake test

运行包括单元测试、功能测试和集成测试在内的所有测试。

rake test:units

运行所有的单元测试。

rake test:functionals

运行所有的功能测试

rake test:integration

运行所有的集成测试。

rake test:recent

运行最近修改过的测试。


rake test:uncommited

运行所有未提交的测试。支持svn和git。

setup和teardown

在一个包含多个测试方法的测试类中,我们可能会包含一些在每个测试运行之前和之后都需要做的工作,都需要执行的一些代码。

比如说创建对象,清理对象之类的。集中在一起便于维护,便于修改,便于阅读。

这样的事情我们可以交给setup和teardown来做。setup就是中的代码在每个测试方法执行之前运行,teardown中的代码会在每个测试方法执行之后运行。

这里我们拿之前做过的一个针对Admin::TagsController的功能测试举例,引入setup和teardown。添加tag是需要登录的,会用到用户信息,需要session中有值,这部分在Admin::TagsController的所有action中都是需要的,而且使用相同就可以了,把这部分放在setup和teardown正合适。

require "test_helper" class Admin::TagsControllerTest < ActionController::TestCase include FactoryGirl::Syntax::Methodsdef setup @user_valid = create(:user_valid) @request.session[:user_id] = @user_valid.id enddef teardown @user_valid = nilenddef test_should_create_tag_successfully tag = build(:tag_valid)assert_difference "Tag.count" dopost :create, {:tag => { :title => tag.title}} end enddef test_should_create_tag_failassert_no_difference "Tag.count" dopost :create, {:tag => { :title => ""}} end end end
而且rails还把setup和teardown实现为callback,这样你就可以通过下面的方式来指定setup和teardown。

a block

a method

a method name as a symbol

a lambda

setup :init teardown do @user_valid = nil endprivate def init@user_valid = create(:user_valid)@request.session[:user_id] = @user_valid.idend
测试routes

assert_routing( "signout", {:controller =>"sessions", :action =>"destroy", :method => :delete} )
def test_route_posts_idcategory = FactoryGirl.create(:category_valid)article = FactoryGirl.create(:post_valid)assert_routing("posts/#{article.id}", {:controller =>"posts", :action => "show", :id => article.id.to_s }) end
本文出自 “突破中的IT结构师” 博客,请务必保留此出处http://virusswb.blog.51cto.com/115214/1079484

查看本栏目更多精彩内容:http://www.bianceng.cn/Programming/project/