Rails测试《三》功能测试functional test2014-03-15功能测试functional test在rails中,针对单个controller中的各个action进行的测试,叫做功能测试。controller处理web的请求,将请求的响应render到view中。功能测试包括的内容web请求是否成功?用户是否被引导进入正确的页面?用户是否成功的验证?响应的模板中是否包含了正确的内容?在给用户的view中是否显示了适当的内容?功能测试分解在使用rails g scaffold post或者rails g controller命令之后,会创建PostsController对应的功能测试文件test/functional/posts_controller_test.rb 。
require "test_helper" class PostsControllerTest < ActionController::TestCase test "should get index" doget :index assert_response :success assert_not_nil assigns(:posts)endend
上面的test针对postscontroller的index。使用http的get方法访问这个index,然后断言响应成功,并且分配一个有效的posts变量。get方法发出web request,把结果加载到response中。get方法有四个参数:你要测试的action,可以是string或者symbol。get "index"或者get :index。可选的hash格式参数,请求的参数,传入action的参数。querystring参数,或者post参数。可选的hash格式参数,传入action的session信息。可选的hash格式参数,flash信息。get(:show, {"id" => "12"}, {"user_id" => 5})调用show这个action,传入的参数是id=12,session信息是user_id=5。get(:view, {"id" => "12"}, nil, {"message" => "booya!"})调用view这个action,传入的参数是id=12,没有session,但是包括一个flash,flash[:message]="booya!"。功能测试中可以使用的请求类型getpostputheaddelete四个hash在一个请求完成之后,你有四个hash可以使用:assigns,在action中返回给view使用的实例变量。cookies,设置的cookies信息。flash,flash对象。session,session信息。除了assigns以外,其他三个hash都可以通过两种方法来访问hash的值,assigns由于历史原因,和其他三个有一点不一样。
flash["gordon"] flash[:gordon] session["shmession"]session[:shmession] cookies["are_good_for_u"] cookies[:are_good_for_u] # Because you can"t use assigns[:something] for historical reasons: assigns["something"]assigns(:something)
三个变量在functional test中有三个变量可以使用:@controller – 处理请求的controller@request – 请求本身@response – 请求的响应本文出自 “突破中的IT结构师” 博客,请务必保留此出处http://virusswb.blog.51cto.com/115214/1075409查看本栏目更多精彩内容:http://www.bianceng.cn/Programming/project/