Spec-Zone.ru › Ruby on Rails 5.0

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

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

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

assert_generates(expected_path, options, defaults={}, extras={}, message=nil) Показать исходный код
# File actionpack/lib/action_dispatch/testing/assertions/routing.rb, line 78
def assert_generates(expected_path, options, defaults={}, extras={}, message=nil)
  if expected_path =~ %r{://}
    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.first == '/'
  end
  # Load routes.rb if it hasn't been loaded.

  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 40
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, которые обычно находятся в строке запроса. Это позволяет убедиться, что значения в строке запроса корректно попадут в хэш params. Чтобы проверить строки запроса, необходимо использовать аргумент 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 122
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, *args, &block) Показать исходный код
# File actionpack/lib/action_dispatch/testing/assertions/routing.rb, line 171
def method_missing(selector, *args, &block)
  if defined?(@controller) && @controller && defined?(@routes) && @routes && @routes.named_routes.route_defined?(selector)
    @controller.send(selector, *args, &block)
  else
    super
  end
end

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

Вызывает метод суперкласса
with_routing() { |routes| ... } Показать исходный код
# File actionpack/lib/action_dispatch/testing/assertions/routing.rb, line 148
def with_routing
  old_routes, @routes = @routes, ActionDispatch::Routing::RouteSet.new
  if defined?(@controller) && @controller
    old_controller, @controller = @controller, @controller.clone
    _routes = @routes

    @controller.singleton_class.include(_routes.url_helpers)

    if @controller.respond_to? :view_context_class
      @controller.view_context_class = Class.new(@controller.view_context_class) do
        include _routes.url_helpers
      end
    end
  end
  yield @routes
ensure
  @routes = old_routes
  if defined?(@controller) && @controller
    @controller = old_controller
  end
end

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

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

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

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

Spec-Zone.ru

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