略過至內容 略過至搜尋

這個類別的實例代表一組請求和回應,由測試處理程序循序執行。由於您可以實例化多個工作階段,並同時執行,因此您也可以(在某些限制範圍內)模擬多個同時使用者與系統互動。

通常,您會使用 Runner#open_session 實例化新的工作階段,而非直接實例化 Session

方法
C
H
N
P
R
U
包含的模組

常數

DEFAULT_HOST = "www.example.com"
 

屬性

[RW] accept

要傳送的 Accept 標頭。

[R] controller

最新請求所使用的控制器實例的參考。

[W] host
[W] host!
[RW] remote_addr

最新請求中使用的 remote_addr

[R] request

最新請求所使用的請求實例的參考。

[RW] request_count

處理的請求數量的執行計數器。

[R] response

最新請求所使用的回應實例的參考。

類別公開方法

new(app)

建立並初始化新的 Session 實例。

# File actionpack/lib/action_dispatch/testing/integration.rb, line 133
def initialize(app)
  super()
  @app = app

  reset!
end

實例公開方法

cookies()

最新回應回傳的 cookie 之對應,且會與下一個請求一起傳送。

# File actionpack/lib/action_dispatch/testing/integration.rb, line 114
def cookies
  _mock_session.cookie_jar
end

host()

最新請求中使用的主機名稱。

# File actionpack/lib/action_dispatch/testing/integration.rb, line 101
def host
  @host || DEFAULT_HOST
end

https!(flag = true)

指定工作階段是否應模擬安全的 HTTPS 請求。

session.https!
session.https!(false)
# File actionpack/lib/action_dispatch/testing/integration.rb, line 180
def https!(flag = true)
  @https = flag
end

https?()

如果工作階段模擬安全 HTTPS 請求,則傳回 true

if session.https?
  ...
end
# File actionpack/lib/action_dispatch/testing/integration.rb, line 189
def https?
  @https
end

process(method, path, params: nil, headers: nil, env: nil, xhr: false, as: nil)

執行實際的請求。

  • method:HTTP 方法(GET、POST、PATCH、PUT、DELETE、HEAD、OPTIONS),表示為符號。

  • path:您要執行請求的 URI(作為 String)。

  • params:您要提供的 HTTP 參數。可以是 nilHash 或以適當方式編碼(application/x-www-form-urlencodedmultipart/form-data)的 String

  • headers:要提供的額外標頭,作為 Hash。將會將標頭合併到 Rack 環境 hash 中。

  • env:要提供的額外環境,作為 Hash。將會將標頭合併到 Rack 環境 hash 中。

  • xhr:如果您要進行 Ajax 請求,請設為 true。新增 XMLHttpRequest 特性的請求標頭,例如 HTTP_X_REQUESTED_WITH。將會將標頭合併到 Rack 環境 hash 中。

  • as:用於編碼具備不同內容類型的請求。預設支援 :json,並會設定適當的請求標頭。將會將標頭合併到 Rack 環境 hash 中。

此方法很少直接使用。在整合測試中,請使用 RequestHelpers#getRequestHelpers#post 或其他標準 HTTP 方法。#process 只有在整合測試中使用未定義方法的請求方法時才需要。

執行請求後,此方法會傳回回應狀態。此外,如果此方法是由 ActionDispatch::IntegrationTest 物件呼叫,該物件的 @response 執行個體變數指標會指向 Response 物件,這個物件可以用於檢查回應的詳細資料。

範例:process :get, ‘/author’,params: { since: 201501011400 }

# File actionpack/lib/action_dispatch/testing/integration.rb, line 225
def process(method, path, params: nil, headers: nil, env: nil, xhr: false, as: nil)
  request_encoder = RequestEncoder.encoder(as)
  headers ||= {}

  if method == :get && as == :json && params
    headers["X-Http-Method-Override"] = "GET"
    method = :post
  end

  if path.include?("://")
    path = build_expanded_path(path) do |location|
      https! URI::HTTPS === location if location.scheme

      if url_host = location.host
        default = Rack::Request::DEFAULT_PORTS[location.scheme]
        url_host += ":#{location.port}" if default != location.port
        host! url_host
      end
    end
  end

  hostname, port = host.split(":")

  request_env = {
    :method => method,
    :params => request_encoder.encode_params(params),

    "SERVER_NAME"     => hostname,
    "SERVER_PORT"     => port || (https? ? "443" : "80"),
    "HTTPS"           => https? ? "on" : "off",
    "rack.url_scheme" => https? ? "https" : "http",

    "REQUEST_URI"    => path,
    "HTTP_HOST"      => host,
    "REMOTE_ADDR"    => remote_addr,
    "HTTP_ACCEPT"    => request_encoder.accept_header || accept
  }

  if request_encoder.content_type
    request_env["CONTENT_TYPE"] = request_encoder.content_type
  end

  wrapped_headers = Http::Headers.from_hash({})
  wrapped_headers.merge!(headers) if headers

  if xhr
    wrapped_headers["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest"
    wrapped_headers["HTTP_ACCEPT"] ||= [Mime[:js], Mime[:html], Mime[:xml], "text/xml", "*/*"].join(", ")
  end

  # This modifies the passed request_env directly.
  if wrapped_headers.present?
    Http::Headers.from_hash(request_env).merge!(wrapped_headers)
  end
  if env.present?
    Http::Headers.from_hash(request_env).merge!(env)
  end

  session = Rack::Test::Session.new(_mock_session)

  # NOTE: rack-test v0.5 doesn't build a default uri correctly Make sure requested
  # path is always a full URI.
  uri = build_full_uri(path, request_env)

  if method == :get && String === request_env[:params]
    # rack-test will needlessly parse and rebuild a :params
    # querystring, using Rack's query parser. At best that's a
    # waste of time; at worst it can change the value.

    uri << "?" << request_env.delete(:params)
  end

  session.request(uri, request_env)

  @request_count += 1
  @request = ActionDispatch::Request.new(session.last_request.env)
  response = _mock_session.last_response
  @response = ActionDispatch::TestResponse.from_response(response)
  @response.request = @request
  @html_document = nil
  @url_options = nil

  @controller = @request.controller_instance

  response.status
end

reset!()

重設執行個體。可用於重設現有工作階段執行個體的狀態資訊,以便可以從全然純淨的狀態使用。

session.reset!
# File actionpack/lib/action_dispatch/testing/integration.rb, line 156
def reset!
  @https = false
  @controller = @request = @response = nil
  @_mock_session = nil
  @request_count = 0
  @url_options = nil

  self.host        = DEFAULT_HOST
  self.remote_addr = "127.0.0.1"
  self.accept      = "text/xml,application/xml,application/xhtml+xml," \
                     "text/html;q=0.9,text/plain;q=0.8,image/png," \
                     "*/*;q=0.5"

  unless defined? @named_routes_configured
    # the helpers are made protected by default--we make them public for easier
    # access during testing and troubleshooting.
    @named_routes_configured = true
  end
end

url_options()

# File actionpack/lib/action_dispatch/testing/integration.rb, line 140
def url_options
  @url_options ||= default_url_options.dup.tap do |url_options|
    url_options.reverse_merge!(controller.url_options) if controller.respond_to?(:url_options)

    if @app.respond_to?(:routes)
      url_options.reverse_merge!(@app.routes.default_url_options)
    end

    url_options.reverse_merge!(host: host, protocol: https? ? "https" : "http")
  end
end