特別なインスタンス変数
Special instance variables
ActionController::TestCaseはテストで使用する以下のインスタンス変数も自動的に供給する
ActionController::TestCase will also automatically provide the following
instance variables for use in the tests:
テストするコントローラーインスタンス
@controller
: The controller instance that will be tested.
ActionController::TestRequestは今のhttpリクエストを代理する。httpリクエスト送信の前にオブジェクトを修正できる。例えば、GETリクエスト送信前にセッションプロパティを設定していいかもしれない
@request
: An ActionController::TestRequest, representing the current HTTP request.
You can modify this object before sending the HTTP request. For example,
you might want to set some session properties before sending a GET
request.
ActionDispatch::TestResponseオブジェクトは最後のhttpレスポンスの応答を代理します。上の例では@responseはpostを呼び出した後、有効になります。いつくかのassert methodsが十分でないなら、詳細にhttpレスポンスを調べるためにこのオブジェクトを使うといいかもしれません
@response
: An ActionDispatch::TestResponse object, representing the response of the
last HTTP response. In the above example,@responsebecomes valid after
callingpost. If the various assert methods are not sufficient, then you
may use this object to inspect the HTTP response in detail.
Basic example
機能テストは次のように記述する
Functional tests are written as follows:
get, post, patch, put, delete, headメソッドはhttpレスポンスをシミュレートします
- First, one uses the
get,post,patch,put,delete, orhead
method to simulate an HTTP request.
期待された現在の状態かどうかを判断します。状態はコントローラーのhttpレスポンス、データベースのコンテンツなどなんでも構いません
- Then, one asserts whether the current state is as expected. "State" can be
anything: the controller's HTTP response, the database contents, etc.
# For example:
#
# 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
#
# You can also send a real document in the simulated HTTP request.
#
# def test_create
# json = {book: { title: "Love Hina" }}.to_json
# post :create, body: json
# end
感想
- @controllerはhttpリクエストを送る前に設定しておく。
- httpメソッド宣言されないと @responseは有効にならない。