Action Controller 测试用例¶ ↑
ActionController 功能测试的超类。功能测试允许您为每个测试方法测试单个控制器操作。
使用集成式控制器测试而非功能式控制器测试。¶ ↑
Rails 鼓励使用集成测试而非功能测试(使用 ActionDispatch::IntegrationTest)。
新的 Rails 应用程序不再生成功能式控制器测试,它们仅用于向后兼容。集成式控制器测试执行实际的请求,而功能式控制器测试仅模拟请求。此外,集成测试与功能测试一样快,并提供许多助手,例如 as、parsed_body,可用于有效测试控制器操作,包括 API 端点。
基本示例¶ ↑
功能测试的编写方式如下:1. 首先,使用 get、post、patch、put、delete 或 head 方法模拟 HTTP 请求。2. 然后,断言当前状态是否符合预期。“状态”可以是任何内容:控制器的 HTTP 响应、数据库内容等。
例如
class BooksControllerTest < ActionController::TestCase def test_create # Simulate a POST response with the given HTTP parameters. post(:create, params: { book: { title: "Love Hina" }}) # Asserts that the controller tried to redirect us to # the created book's URI. assert_response :found # Asserts that the controller really put the book in the database. assert_not_nil Book.find_by(title: "Love Hina") end end
您也可以在模拟的 HTTP 请求中发送真实的文档。
def test_create json = {book: { title: "Love Hina" }}.to_json post :create, body: json end
特殊实例变量¶ ↑
ActionController::TestCase 还将自动提供以下实例变量供测试使用
- @controller
-
将被测试的控制器实例。
- @request
-
一个 ActionController::TestRequest,代表当前的 HTTP 请求。您可以在发送 HTTP 请求之前修改此对象。例如,您可能希望在发送 GET 请求之前设置一些会话属性。
- @response
-
一个
ActionDispatch::TestResponse对象,代表最后一个 HTTP 响应的响应。在上例中,调用post后@response会生效。如果各种断言方法不够用,您可以使用此对象详细检查 HTTP 响应。
控制器自动推断¶ ↑
ActionController::TestCase 将根据测试类名自动推断被测试的控制器。如果无法从测试类名推断出控制器,您可以显式使用 tests 进行设置。
class SpecialEdgeCaseWidgetsControllerTest < ActionController::TestCase tests WidgetController end
测试控制器内部¶ ↑
除了这些特定的断言之外,您还可以轻松访问常规 test/unit 断言可以使用的各种集合。这些集合是
-
session: 存储在会话中的对象。
-
flash: 当前会话中的 flash 对象。
-
cookies: 在此请求中发送给用户的
Cookies。
这些集合可以像任何其他哈希一样使用
assert_equal "Dave", cookies[:name] # makes sure that a cookie called :name was set as "Dave" assert flash.empty? # makes sure that there's nothing in the flash
除了这些集合之外,您还可以获得给定操作重定向到的完整 URL,该 URL 可在 redirect_to_url 中找到。
对于同一控制器内的重定向,您甚至可以调用 follow_redirect,重定向将被跟随,触发另一个操作调用,然后可以对其进行断言。
操作会话和 cookie 变量¶ ↑
有时您需要为测试设置会话和 cookie 变量。只需将值分配给 session 或 cookie 集合即可完成此操作
session[:key] = "value" cookies[:key] = "value"
要清除测试的 cookie,只需清除 cookie 集合即可
cookies.clear
测试命名路由¶ ↑
如果您正在使用命名路由,可以直接在测试用例中使用原始命名路由的方法轻松地测试它们。
assert_redirected_to page_url(title: 'foo')
Attributes
| [RW] | executor_around_each_request |