Spec-Zone.ru › Ruby on Rails 7.2

модуль ActionDispatch::Assertions::RoutingAssertions

Набор утверждений для проверки маршрутов, сгенерированных Rails, и обработки запросов к ним.

Публичные методы экземпляра

assert_generates(expected_path, options, defaults = {}, extras = {}, message = nil) Показать исходный код
# File actionpack/lib/action_dispatch/testing/assertions/routing.rb, line 204
def assert_generates(expected_path, options, defaults = {}, extras = {}, message = nil)
  if expected_path.include?("://")
    fail_on(URI::InvalidURIError, message) do
      uri = URI.parse(expected_path)
      expected_path = uri.path.to_s.empty? ? "/" : uri.path
    end
  else
    expected_path = "/#{expected_path}" unless expected_path.start_with?("/")
  end

  options = options.clone
  generated_path, query_string_keys = @routes.generate_extras(options, defaults)
  found_extras = options.reject { |k, _| ! query_string_keys.include? k }

  msg = message || sprintf("found extras <%s>, not <%s>", found_extras, extras)
  assert_equal(extras, found_extras, msg)

  msg = message || sprintf("The generated path <%s> did not match <%s>", generated_path,
      expected_path)
  assert_equal(expected_path, generated_path, msg)
end

Утверждает, что предоставленные параметры могут быть использованы для генерации указанного пути. Это обратное assert_recognizes. Параметр extras используется для указания имени и значений дополнительных параметров запроса, которые будут находиться в строке запроса. Параметр message позволяет указать пользовательское сообщение об ошибке для случаев неудачи утверждения.

Параметр defaults не используется.

# Asserts that the default action is generated for a route with no action
assert_generates "/items", controller: "items", action: "index"

# Tests that the list action is properly routed
assert_generates "/items/list", controller: "items", action: "list"

# Tests the generation of a route with a parameter
assert_generates "/items/list/1", { controller: "items", action: "list", id: "1" }

# Asserts that the generated route gives us our custom route
assert_generates "changesets/12", { controller: 'scm', action: 'show_diff', revision: "12" }
assert_recognizes(expected_options, path, extras = {}, msg = nil) Показать исходный код
# File actionpack/lib/action_dispatch/testing/assertions/routing.rb, line 164
def assert_recognizes(expected_options, path, extras = {}, msg = nil)
  if path.is_a?(Hash) && path[:method].to_s == "all"
    [:get, :post, :put, :delete].each do |method|
      assert_recognizes(expected_options, path.merge(method: method), extras, msg)
    end
  else
    request = recognized_request_for(path, extras, msg)

    expected_options = expected_options.clone

    expected_options.stringify_keys!

    msg = message(msg, "") {
      sprintf("The recognized options <%s> did not match <%s>, difference:",
              request.path_parameters, expected_options)
    }

    assert_equal(expected_options, request.path_parameters, msg)
  end
end

Утверждает, что маршрутизация данного path была обработана корректно и что разобранные параметры (переданные в хеше expected_options ) совпадают с path. В основном, это утверждение, что Rails распознает маршрут, заданный expected_options.

Передайте хеш во втором аргументе (path) для указания метода запроса. Это полезно для маршрутов, требующих определённого HTTP-метода. Хеш должен содержать :path с путём входящего запроса и :method с необходимым HTTP-методом.

# Asserts that POSTing to /items will call the create action on ItemsController
assert_recognizes({controller: 'items', action: 'create'}, {path: 'items', method: :post})

Вы также можете передать extras с хешем, содержащим параметры URL, которые обычно находятся в строке запроса. Это можно использовать для проверки того, что значения в строке запроса корректно попадут в хеш параметров. Для проверки строк запроса необходимо использовать аргумент extras, потому что добавление строки запроса непосредственно к пути не сработает. Например:

# Asserts that a path of '/items/list/1?view=print' returns the correct options
assert_recognizes({controller: 'items', action: 'list', id: '1', view: 'print'}, 'items/list/1', { view: "print" })

Параметр message позволяет указать сообщение об ошибке, отображаемое при неудачном утверждении.

# Check the default route (i.e., the index action)
assert_recognizes({controller: 'items', action: 'index'}, 'items')

# Test a specific action
assert_recognizes({controller: 'items', action: 'list'}, 'items/list')

# Test an action with a parameter
assert_recognizes({controller: 'items', action: 'destroy', id: '1'}, 'items/destroy/1')

# Test a custom route
assert_recognizes({controller: 'items', action: 'show', id: '1'}, 'view/item1')
assert_routing(path, options, defaults = {}, extras = {}, message = nil) Показать исходный код
# File actionpack/lib/action_dispatch/testing/assertions/routing.rb, line 248
def assert_routing(path, options, defaults = {}, extras = {}, message = nil)
  assert_recognizes(options, path, extras, message)

  controller, default_controller = options[:controller], defaults[:controller]
  if controller && controller.include?(?/) && default_controller && default_controller.include?(?/)
    options[:controller] = "/#{controller}"
  end

  generate_options = options.dup.delete_if { |k, _| defaults.key?(k) }
  assert_generates(path.is_a?(Hash) ? path[:path] : path, generate_options, defaults, extras, message)
end

Утверждает, что путь и параметры совпадают в обоих направлениях; другими словами, проверяет, что path генерирует options , а затем, что options генерирует path . Это в сущности объединяет assert_recognizes и assert_generates в один шаг.

Хеш extras позволяет задать параметры, которые обычно передаются в действии в качестве строки запроса. Параметр message позволяет указать пользовательское сообщение об ошибке при неудачном утверждении.

# Asserts a basic route: a controller with the default action (index)
assert_routing '/home', controller: 'home', action: 'index'

# Test a route generated with a specific controller, action, and parameter (id)
assert_routing '/entries/show/23', controller: 'entries', action: 'show', id: 23

# Asserts a basic route (controller + default action), with an error message if it fails
assert_routing '/store', { controller: 'store', action: 'index' }, {}, {}, 'Route for store index not generated properly'

# Tests a route, providing a defaults hash
assert_routing 'controller/action/9', {id: "9", item: "square"}, {controller: "controller", action: "action"}, {}, {item: "square"}

# Tests a route with an HTTP method
assert_routing({ method: 'put', path: '/product/321' }, { controller: "product", action: "update", id: "321" })
method_missing(selector, ...) Показать исходный код
# File actionpack/lib/action_dispatch/testing/assertions/routing.rb, line 261
def method_missing(selector, ...)
  if @controller && @routes&.named_routes&.route_defined?(selector)
    @controller.public_send(selector, ...)
  else
    super
  end
end

МАРШРУТЫ TODO: Эти утверждения действительно должны работать в контексте интеграции

Вызывает метод суперкласса
with_routing(&block) Показать исходный код
# File actionpack/lib/action_dispatch/testing/assertions/routing.rb, line 121
def with_routing(&block)
  old_routes, old_controller = @routes, @controller
  create_routes(&block)
ensure
  reset_routes(old_routes, old_controller)
end

Помощник для облегчения тестирования различных конфигураций маршрутов. Этот метод временно заменяет @routes экземпляром нового RouteSet.

Новый экземпляр передаётся в переданный блок. Обычно блок создаёт некоторые маршруты, используя set.draw { match ... }:

with_routing do |set|
  set.draw do
    resources :users
  end
  assert_equal "/users", users_path
end

© 2004–2021 David Heinemeier Hansson
Licensed under the MIT License.

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API