Rails测试《三》功能测试functional test
功能测试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'classPostsControllerTest<ActionController::TestCasetest"shouldgetindex"doget:indexassert_response:successassert_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!"。
功能测试中可以使用的请求类型
get post put head delete四个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]#Becauseyoucan'tuseassigns[:something]forhistoricalreasons:assigns["something"]assigns(:something)
三个变量
在functional test中有三个变量可以使用:
@controller – 处理请求的controller @request – 请求本身 @response – 请求的响应
参考文献
1.http://guides.rubyonrails.org/testing.html
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。