модуль ActionDispatch::Assertions::RoutingAssertions
Набор утверждений для проверки маршрутов, сгенерированных Rails, и обработки запросов, отправленных к ним.
Публичные методы экземпляра
# File actionpack/lib/action_dispatch/testing/assertions/routing.rb, line 85
def assert_generates(expected_path, options, defaults = {}, extras = {}, message = nil)
if %r{://}.match?(expected_path)
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" }
# File actionpack/lib/action_dispatch/testing/assertions/routing.rb, line 47
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')
# File actionpack/lib/action_dispatch/testing/assertions/routing.rb, line 128
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" })
# File actionpack/lib/action_dispatch/testing/assertions/routing.rb, line 183
def method_missing(selector, *args, &block)
if defined?(@controller) && @controller && defined?(@routes) && @routes && @routes.named_routes.route_defined?(selector)
@controller.public_send(selector, *args, &block)
else
super
end
end МАРШРУТЫ TODO: Эти утверждения должны действительно работать в контексте интеграции
# File actionpack/lib/action_dispatch/testing/assertions/routing.rb, line 153
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
view_context_class = Class.new(@controller.view_context_class) do
include _routes.url_helpers
end
custom_view_context = Module.new {
define_method(:view_context_class) do
view_context_class
end
}
@controller.extend(custom_view_context)
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–2020 David Heinemeier Hansson
Licensed under the MIT License.