0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

テスト時のインスタンス変数

Last updated at Posted at 2025-02-02

特別なインスタンス変数

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レスポンスの応答を代理します。上の例では@responsepostを呼び出した後、有効になります。いつくかのassert methodsが十分でないなら、詳細にhttpレスポンスを調べるためにこのオブジェクトを使うといいかもしれません

@response
: An ActionDispatch::TestResponse object, representing the response of the
last HTTP response. In the above example, @response becomes valid after
calling post. 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レスポンスをシミュレートします

  1. First, one uses the get, post, patch, put, delete, or head
    method to simulate an HTTP request.

期待された現在の状態かどうかを判断します。状態はコントローラーのhttpレスポンス、データベースのコンテンツなどなんでも構いません

  1. 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は有効にならない。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?