Welcome

首页 / 软件开发 / 数据结构与算法 / Rails测试《九》集成测试integration test

Rails测试《九》集成测试integration test2014-03-15开场白

今天我们来熟悉一下rails的集成测试integration test。

简介

集成测试主要是测试多个controller之间的交互,以及测试应用中比较重要的工作流程,验证这些工作流程是否符合预期的设想。

不像单元测试和功能测试,是自动添加的。集成测试是需要我们手动添加的,rails提供了一个命令

rails generate integration_test

通过命令就可以在test/integration文件夹创建集成测试。

$ rails generate integration_test user_flows existstest/integration/ createtest/integration/user_flows_test.rb
我们先来了解一些集成测试中常用的帮助方法。

https?

如果session正在模拟https请求,就返回true。

https!

允许你模拟https请求。

host!

允许你在下一次的请求中设置host name。

redirect?

如果上一次请求是一个跳转,就返回true。

follow_redirect!

紧跟着一个跳转的响应

request_via_redirect(http_method, path, [parameters], [headers])

向指定的path发送http请求,可选parameters,可选headers,然后跟着一个跳转。

post_via_redirect(path, [parameters], [headers])

向指定的path发送post请求,可选parameters,可选headers,然后跟着一个跳转。

get_via_redirect(path, [parameters], [headers])

向指定的path发送get请求,可选parameters,可选headers,然后跟着一个跳转。

put_via_redirect(path, [parameters], [headers])

向指定的path发送put请求,可选parameters,可选headers,然后跟着一个跳转。

delete_via_redirect(path, [parameters], [headers])

向指定的path发送delete请求,可选parameters,可选headers,然后跟着一个跳转。

open_session

开启一个新的session

示例

让我们在创建好的集成测试文件test/integration/user_flows_test.rb中添加一些代码。

require "test_helper" class UserFlowsTest < ActionDispatch::IntegrationTest include FactoryGirl::Syntax::Methodsdef test_admin_login_and_browse_posts user = FactoryGirl.create(:user_valid)get "/signin"assert_response(200)post_via_redirect("sessions", {:user=>{:email=> user.email, :password => user.password}}) assert_equal "/", path assert_equal "sign in successfully", flash[:notice]get "admin/posts"assert_response(200) assert assigns(:posts)endend