1 require 'abstract_unit'
2 require 'controller/fake_controllers'
3 require 'action_controller/routing'
5 class MilestonesController
< ActionController
::Base
6 def index() head
:ok end
7 alias_method
:show, :index
8 def rescue_action(e
) raise e
end
11 RunTimeTests
= ARGV.include? 'time'
12 ROUTING
= ActionController
::Routing
14 class ROUTING
::RouteBuilder
15 attr_reader
:warn_output
18 (@warn_output ||= []) << msg
22 # See RFC 3986, section 3.3 for allowed path characters.
23 class UriReservedCharactersRoutingTest
< Test
::Unit::TestCase
25 ActionController
::Routing.use_controllers!
['controller']
26 @set = ActionController
::Routing::RouteSet.new
28 map
.connect
':controller/:action/:variable/*additional'
31 safe
, unsafe
= %w(: @
& = + $
, ;), %w(^
/ ? # [ ])
32 hex
= unsafe
.map
{ |char
| '%' + char
.unpack('H2').first
.upcase
}
34 @segment = "#{safe.join}#{unsafe.join}".freeze
35 @escaped = "#{safe.join}#{hex.join}".freeze
38 def test_route_generation_escapes_unsafe_path_characters
39 assert_equal
"/contr#{@segment}oller/act#{@escaped}ion/var#{@escaped}iable/add#{@escaped}itional-1/add#{@escaped}itional-2",
40 @set.generate(:controller => "contr#{@segment}oller",
41 :action => "act#{@segment}ion",
42 :variable => "var#{@segment}iable",
43 :additional => ["add#{@segment}itional-1", "add#{@segment}itional-2"])
46 def test_route_recognition_unescapes_path_components
47 options
= { :controller => "controller",
48 :action => "act#{@segment}ion",
49 :variable => "var#{@segment}iable",
50 :additional => ["add#{@segment}itional-1", "add#{@segment}itional-2"] }
51 assert_equal options
, @set.recognize_path("/controller/act#{@escaped}ion/var#{@escaped}iable/add#{@escaped}itional-1/add#{@escaped}itional-2")
54 def test_route_generation_allows_passing_non_string_values_to_generated_helper
55 assert_equal
"/controller/action/variable/1/2", @set.generate(:controller => "controller",
57 :variable => "variable",
58 :additional => [1, 2])
62 class SegmentTest
< Test
::Unit::TestCase
63 def test_first_segment_should_interpolate_for_structure
64 s
= ROUTING
::Segment.new
65 def s
.interpolation_statement(array
) 'hello' end
66 assert_equal
'hello', s
.continue_string_structure([])
69 def test_interpolation_statement
70 s
= ROUTING
::StaticSegment.new("Hello")
71 assert_equal
"Hello", eval(s
.interpolation_statement([]))
72 assert_equal
"HelloHello", eval(s
.interpolation_statement([s
]))
74 s2
= ROUTING
::StaticSegment.new("-")
75 assert_equal
"Hello-Hello", eval(s
.interpolation_statement([s
, s2
]))
77 s3
= ROUTING
::StaticSegment.new("World")
78 assert_equal
"Hello-World", eval(s3
.interpolation_statement([s
, s2
]))
82 class StaticSegmentTest
< Test
::Unit::TestCase
83 def test_interpolation_chunk_should_respect_raw
84 s
= ROUTING
::StaticSegment.new('Hello World')
86 assert_equal
'Hello%20World', s
.interpolation_chunk
88 s
= ROUTING
::StaticSegment.new('Hello World', :raw => true)
90 assert_equal
'Hello World', s
.interpolation_chunk
93 def test_regexp_chunk_should_escape_specials
94 s
= ROUTING
::StaticSegment.new('Hello*World')
95 assert_equal
'Hello\*World', s
.regexp_chunk
97 s
= ROUTING
::StaticSegment.new('HelloWorld')
98 assert_equal
'HelloWorld', s
.regexp_chunk
101 def test_regexp_chunk_should_add_question_mark_for_optionals
102 s
= ROUTING
::StaticSegment.new("/", :optional => true)
103 assert_equal
"/?", s
.regexp_chunk
105 s
= ROUTING
::StaticSegment.new("hello", :optional => true)
106 assert_equal
"(?:hello)?", s
.regexp_chunk
110 class DynamicSegmentTest
< Test
::Unit::TestCase
111 def segment(options
= {})
113 @segment = ROUTING
::DynamicSegment.new(:a, options
)
118 def test_extract_value
119 s
= ROUTING
::DynamicSegment.new(:a)
121 hash
= {:a => '10', :b => '20'}
122 assert_equal
'10', eval(s
.extract_value
)
125 assert_equal
nil, eval(s
.extract_value
)
128 assert_equal
'20', eval(s
.extract_value
)
131 def test_default_local_name
132 assert_equal
'a_value', segment
.local_name
,
133 "Unexpected name -- all value_check tests will fail!"
136 def test_presence_value_check
138 assert eval(segment.value_check)
141 def test_regexp_value_check_rejects_nil
142 segment = segment(:regexp => /\d+/)
145 assert !
eval(segment
.value_check
)
148 def test_optional_regexp_value_check_should_accept_nil
149 segment
= segment(:regexp => /\d+/, :optional => true)
152 assert
eval(segment
.value_check
)
155 def test_regexp_value_check_rejects_no_match
156 segment
= segment(:regexp => /\d+/)
158 a_value
= "Hello20World"
159 assert !
eval(segment
.value_check
)
162 assert !
eval(segment
.value_check
)
165 def test_regexp_value_check_accepts_match
166 segment
= segment(:regexp => /\d+/)
168 assert
eval(segment
.value_check
)
171 def test_value_check_fails_on_nil
173 assert !
eval(segment
.value_check
)
176 def test_optional_value_needs_no_check
177 segment
= segment(:optional => true)
180 assert_equal
nil, segment
.value_check
183 def test_regexp_value_check_should_accept_match_with_default
184 segment
= segment(:regexp => /\d+/, :default => '200')
187 assert
eval(segment
.value_check
)
190 def test_expiry_should_not_trigger_once_expired
192 hash
= merged
= {:a => 2, :b => 3}
194 expire_on
= Hash
.new
{ raise 'No!!!
' }
196 eval(segment.expiry_statement)
198 flunk "Expiry check should not have occurred!"
201 def test_expiry_should_occur_according_to_expire_on
203 hash = merged = {:a => 2, :b => 3}
206 expire_on = {:b => true, :a => false}
207 eval(segment.expiry_statement)
209 assert_equal({:a => 2, :b => 3}, hash
)
211 expire_on
= {:b => true, :a => true}
212 eval(segment
.expiry_statement
)
214 assert_equal({:b => 3}, hash
)
217 def test_extraction_code_should_return_on_nil
218 hash
= merged
= {:b => 3}
222 # Local jump because of return inside eval.
223 assert_raises(LocalJumpError
) { eval(segment
.extraction_code
) }
226 def test_extraction_code_should_return_on_mismatch
227 segment
= segment(:regexp => /\d+/)
228 hash
= merged
= {:a => 'Hi', :b => '3'}
229 options
= {:b => '3'}
232 # Local jump because of return inside eval.
233 assert_raises(LocalJumpError
) { eval(segment
.extraction_code
) }
236 def test_extraction_code_should_accept_value_and_set_local
237 hash
= merged
= {:a => 'Hi', :b => '3'}
238 options
= {:b => '3'}
242 eval(segment
.extraction_code
)
243 assert_equal
'Hi', a_value
246 def test_extraction_should_work_without_value_check
247 segment
.default
= 'hi'
248 hash
= merged
= {:b => '3'}
249 options
= {:b => '3'}
253 eval(segment
.extraction_code
)
254 assert_equal
'hi', a_value
257 def test_extraction_code_should_perform_expiry
259 hash
= merged
= {:a => 'Hi', :b => '3'}
260 options
= {:b => '3'}
261 expire_on
= {:a => true}
264 eval(segment
.extraction_code
)
265 assert_equal
'Hi', a_value
267 assert_equal options
, hash
270 def test_interpolation_chunk_should_replace_value
272 assert_equal a_value
, eval(%("#{segment.interpolation_chunk}"))
275 def test_interpolation_chunk_should_accept_nil
277 assert_equal
'', eval(%("#{segment.interpolation_chunk('a_value')}"))
280 def test_value_regexp_should_be_nil_without_regexp
281 assert_equal
nil, segment
.value_regexp
284 def test_value_regexp_should_match_exacly
285 segment
= segment(:regexp => /\d+/)
286 assert_no_match segment
.value_regexp
, "Hello 10 World"
287 assert_no_match segment
.value_regexp
, "Hello 10"
288 assert_no_match segment
.value_regexp
, "10 World"
289 assert_match segment
.value_regexp
, "10"
292 def test_regexp_chunk_should_return_string
293 segment
= segment(:regexp => /\d+/)
294 assert_kind_of String
, segment
.regexp_chunk
297 def test_build_pattern_non_optional_with_no_captures
299 a_segment
= ROUTING
::DynamicSegment.new(nil, :regexp => /\d+/)
300 assert_equal
"(\\d+)stuff
", a_segment.build_pattern('stuff')
303 def test_build_pattern_non_optional_with_captures
305 a_segment = ROUTING::DynamicSegment.new(nil, :regexp => /(\d+)(.*?)/)
306 assert_equal
"((\\d+)(.*?))stuff
", a_segment.build_pattern('stuff')
309 def test_optionality_implied
310 a_segment = ROUTING::DynamicSegment.new(:id)
311 assert a_segment.optionality_implied?
313 a_segment = ROUTING::DynamicSegment.new(:action)
314 assert a_segment.optionality_implied?
317 def test_modifiers_must_be_handled_sensibly
318 a_segment = ROUTING::DynamicSegment.new(nil, :regexp => /david|jamis/i)
319 assert_equal "((?i-mx
:david|jamis
))stuff
", a_segment.build_pattern('stuff')
320 a_segment = ROUTING::DynamicSegment.new(nil, :regexp => /david|jamis/x)
321 assert_equal "((?x-mi
:david|jamis
))stuff
", a_segment.build_pattern('stuff')
322 a_segment = ROUTING::DynamicSegment.new(nil, :regexp => /david|jamis/)
323 assert_equal "(david
|jamis
)stuff
", a_segment.build_pattern('stuff')
327 class ControllerSegmentTest < Test::Unit::TestCase
328 def test_regexp_should_only_match_possible_controllers
329 ActionController::Routing.with_controllers %w(admin/accounts admin/users account pages) do
330 cs = ROUTING::ControllerSegment.new :controller
331 regexp = %r{\A#{cs.regexp_chunk}\Z}
333 ActionController::Routing.possible_controllers.each do |name|
334 assert_match regexp, name
335 assert_no_match regexp, "#{name}_fake
"
337 match = regexp.match name
338 assert_equal name, match[1]
344 class RouteBuilderTest < Test::Unit::TestCase
346 @builder ||= ROUTING::RouteBuilder.new
349 def build(path, options)
350 builder.build(path, options)
353 def test_options_should_not_be_modified
354 requirements1 = { :id => /\w+/, :controller => /(?:[a-z](?:-?[a-z]+)*)/ }
355 requirements2
= requirements1
.dup
357 assert_equal requirements1
, requirements2
359 with_options(:controller => 'folder',
360 :requirements => requirements2
) do |m
|
361 m
.build
'folders/new', :action => 'new'
364 assert_equal requirements1
, requirements2
367 def test_segment_for_static
368 segment
, rest
= builder
.segment_for
'ulysses'
369 assert_equal
'', rest
370 assert_kind_of ROUTING
::StaticSegment, segment
371 assert_equal
'ulysses', segment
.value
374 def test_segment_for_action
375 segment
, rest
= builder
.segment_for
':action'
376 assert_equal
'', rest
377 assert_kind_of ROUTING
::DynamicSegment, segment
378 assert_equal
:action, segment
.key
379 assert_equal
'index', segment
.default
382 def test_segment_for_dynamic
383 segment
, rest
= builder
.segment_for
':login'
384 assert_equal
'', rest
385 assert_kind_of ROUTING
::DynamicSegment, segment
386 assert_equal
:login, segment
.key
387 assert_equal
nil, segment
.default
388 assert ! segment
.optional
?
391 def test_segment_for_with_rest
392 segment
, rest
= builder
.segment_for
':login/:action'
393 assert_equal
:login, segment
.key
394 assert_equal
'/:action', rest
395 segment
, rest
= builder
.segment_for rest
396 assert_equal
'/', segment
.value
397 assert_equal
':action', rest
398 segment
, rest
= builder
.segment_for rest
399 assert_equal
:action, segment
.key
400 assert_equal
'', rest
403 def test_segments_for
404 segments
= builder
.segments_for_route_path
'/:controller/:action/:id'
406 assert_kind_of ROUTING
::DividerSegment, segments
[0]
407 assert_equal
'/', segments
[2].value
409 assert_kind_of ROUTING
::DynamicSegment, segments
[1]
410 assert_equal
:controller, segments
[1].key
412 assert_kind_of ROUTING
::DividerSegment, segments
[2]
413 assert_equal
'/', segments
[2].value
415 assert_kind_of ROUTING
::DynamicSegment, segments
[3]
416 assert_equal
:action, segments
[3].key
418 assert_kind_of ROUTING
::DividerSegment, segments
[4]
419 assert_equal
'/', segments
[4].value
421 assert_kind_of ROUTING
::DynamicSegment, segments
[5]
422 assert_equal
:id, segments
[5].key
425 def test_segment_for_action
426 s
, r
= builder
.segment_for(':action/something/else')
427 assert_equal
'/something/else', r
428 assert_equal
:action, s
.key
431 def test_action_default_should_not_trigger_on_prefix
432 s
, r
= builder
.segment_for
':action_name/something/else'
433 assert_equal
'/something/else', r
434 assert_equal
:action_name, s
.key
435 assert_equal
nil, s
.default
438 def test_divide_route_options
439 segments
= builder
.segments_for_route_path
'/cars/:action/:person/:car/'
440 defaults
, requirements
= builder
.divide_route_options(segments
,
441 :action => 'buy', :person => /\w+/, :car => /\w+/,
442 :defaults => {:person => nil, :car => nil}
445 assert_equal({:action => 'buy', :person => nil, :car => nil}, defaults
)
446 assert_equal({:person => /\w+/, :car => /\w+/}, requirements
)
449 def test_assign_route_options
450 segments
= builder
.segments_for_route_path
'/cars/:action/:person/:car/'
451 defaults
= {:action => 'buy', :person => nil, :car => nil}
452 requirements
= {:person => /\w+/, :car => /\w+/}
454 route_requirements
= builder
.assign_route_options(segments
, defaults
, requirements
)
455 assert_equal({}, route_requirements
)
457 assert_equal
:action, segments
[3].key
458 assert_equal
'buy', segments
[3].default
460 assert_equal
:person, segments
[5].key
461 assert_equal
%r
/\w+/, segments
[5].regexp
462 assert segments
[5].optional
?
464 assert_equal
:car, segments
[7].key
465 assert_equal
%r
/\w+/, segments
[7].regexp
466 assert segments
[7].optional
?
469 def test_assign_route_options_with_anchor_chars
470 segments
= builder
.segments_for_route_path
'/cars/:action/:person/:car/'
471 defaults
= {:action => 'buy', :person => nil, :car => nil}
472 requirements
= {:person => /\w+/, :car => /^\w+$/}
474 assert_raises ArgumentError
do
475 route_requirements
= builder
.assign_route_options(segments
, defaults
, requirements
)
478 requirements
[:car] = /[^\/]+
/
479 route_requirements
= builder
.assign_route_options(segments
, defaults
, requirements
)
482 def test_optional_segments_preceding_required_segments
483 segments
= builder
.segments_for_route_path
'/cars/:action/:person/:car/'
484 defaults
= {:action => 'buy', :person => nil, :car => "model-t"}
485 assert builder
.assign_route_options(segments
, defaults
, {}).empty
?
487 0.upto(1) { |i
| assert !segments
[i
].optional
?, "segment #{i} is optional and it shouldn't be" }
488 assert segments
[2].optional
?
490 assert_equal
nil, builder
.warn_output
# should only warn on the :person segment
493 def test_segmentation_of_dot_path
494 segments
= builder
.segments_for_route_path
'/books/:action.rss'
495 assert builder
.assign_route_options(segments
, {}, {}).empty
?
496 assert_equal
6, segments
.length
# "/", "books", "/", ":action", ".", "rss"
497 assert !segments
.any
? { |seg
| seg
.optional
? }
500 def test_segmentation_of_dynamic_dot_path
501 segments
= builder
.segments_for_route_path
'/books/:action.:format'
502 assert builder
.assign_route_options(segments
, {}, {}).empty
?
503 assert_equal
6, segments
.length
# "/", "books", "/", ":action", ".", ":format"
504 assert !segments
.any
? { |seg
| seg
.optional
? }
505 assert_kind_of ROUTING
::DynamicSegment, segments
.last
508 def test_assignment_of_default_options
509 segments
= builder
.segments_for_route_path
'/:controller/:action/:id/'
510 action
, id
= segments
[-4], segments
[-2]
512 assert_equal
:action, action
.key
513 assert_equal
:id, id
.key
514 assert ! action
.optional
?
515 assert ! id
.optional
?
517 builder
.assign_default_route_options(segments
)
519 assert_equal
'index', action
.default
520 assert action
.optional
?
524 def test_assignment_of_default_options_respects_existing_defaults
525 segments
= builder
.segments_for_route_path
'/:controller/:action/:id/'
526 action
, id
= segments
[-4], segments
[-2]
528 assert_equal
:action, action
.key
529 assert_equal
:id, id
.key
530 action
.default
= 'show'
531 action
.is_optional
= true
533 id
.default
= 'Welcome'
534 id
.is_optional
= true
536 builder
.assign_default_route_options(segments
)
538 assert_equal
'show', action
.default
539 assert action
.optional
?
540 assert_equal
'Welcome', id
.default
544 def test_assignment_of_default_options_respects_regexps
545 segments
= builder
.segments_for_route_path
'/:controller/:action/:id/'
546 action
= segments
[-4]
548 assert_equal
:action, action
.key
549 segments
[-4] = ROUTING
::DynamicSegment.new(:action, :regexp => /show|in/)
551 builder
.assign_default_route_options(segments
)
553 assert_equal
nil, action
.default
554 assert ! action
.optional
?
557 def test_assignment_of_is_optional_when_default
558 segments
= builder
.segments_for_route_path
'/books/:action.rss'
559 assert_equal segments
[3].key
, :action
560 segments
[3].default
= 'changes'
561 builder
.ensure_required_segments(segments
)
562 assert ! segments
[3].optional
?
565 def test_is_optional_is_assigned_to_default_segments
566 segments
= builder
.segments_for_route_path
'/books/:action'
567 builder
.assign_route_options(segments
, {:action => 'index'}, {})
569 assert_equal segments
[3].key
, :action
570 assert segments
[3].optional
?
571 assert_kind_of ROUTING
::DividerSegment, segments
[2]
572 assert segments
[2].optional
?
575 # XXX is optional not being set right?
576 # /blah/:defaulted_segment <-- is the second slash optional? it should be.
579 ActionController
::Routing.with_controllers
%w(users pages
) do
580 r
= builder
.build
'/:controller/:action/:id/', :action => nil
582 [0, 2, 4].each
do |i
|
583 assert_kind_of ROUTING
::DividerSegment, r
.segments
[i
]
584 assert_equal
'/', r
.segments
[i
].value
585 assert r
.segments
[i
].optional
? if i
> 1
588 assert_kind_of ROUTING
::DynamicSegment, r
.segments
[1]
589 assert_equal
:controller, r
.segments
[1].key
590 assert_equal
nil, r
.segments
[1].default
592 assert_kind_of ROUTING
::DynamicSegment, r
.segments
[3]
593 assert_equal
:action, r
.segments
[3].key
594 assert_equal
'index', r
.segments
[3].default
596 assert_kind_of ROUTING
::DynamicSegment, r
.segments
[5]
597 assert_equal
:id, r
.segments
[5].key
598 assert r
.segments
[5].optional
?
602 def test_slashes_are_implied
604 builder
.build('/:controller/:action/:id/', :action => nil),
605 builder
.build('/:controller/:action/:id', :action => nil),
606 builder
.build(':controller/:action/:id', :action => nil),
607 builder
.build('/:controller/:action/:id/', :action => nil)
609 expected
= routes
.first
.segments
.length
610 routes
.each_with_index
do |route
, i
|
611 found
= route
.segments
.length
612 assert_equal expected
, found
, "Route #{i + 1} has #{found} segments, expected #{expected}"
617 class RoutingTest
< Test
::Unit::TestCase
618 def test_possible_controllers
619 true_controller_paths
= ActionController
::Routing.controller_paths
621 ActionController
::Routing.use_controllers!
nil
624 Object
.send(:const_set, :RAILS_ROOT, File
.dirname(__FILE__
) +
'/controller_fixtures')
627 ActionController
::Routing.controller_paths
= [
628 RAILS_ROOT
, RAILS_ROOT +
'/app/controllers', RAILS_ROOT +
'/vendor/plugins/bad_plugin/lib'
631 assert_equal
["admin/user", "plugin", "user"], ActionController
::Routing.possible_controllers
.sort
633 if true_controller_paths
634 ActionController
::Routing.controller_paths
= true_controller_paths
636 ActionController
::Routing.use_controllers!
nil
637 Object
.send(:remove_const, :RAILS_ROOT) rescue nil
640 def test_possible_controllers_are_reset_on_each_load
641 true_possible_controllers
= ActionController
::Routing.possible_controllers
642 true_controller_paths
= ActionController
::Routing.controller_paths
644 ActionController
::Routing.use_controllers!
nil
645 root
= File
.dirname(__FILE__
) +
'/controller_fixtures'
647 ActionController
::Routing.controller_paths
= []
648 assert_equal
[], ActionController
::Routing.possible_controllers
650 ActionController
::Routing.controller_paths
= [
651 root
, root +
'/app/controllers', root +
'/vendor/plugins/bad_plugin/lib'
653 ActionController
::Routing::Routes.load!
655 assert_equal
["admin/user", "plugin", "user"], ActionController
::Routing.possible_controllers
.sort
657 ActionController
::Routing.controller_paths
= true_controller_paths
658 ActionController
::Routing.use_controllers! true_possible_controllers
659 Object
.send(:remove_const, :RAILS_ROOT) rescue nil
661 ActionController
::Routing::Routes.clear!
662 ActionController
::Routing::Routes.load_routes!
665 def test_with_controllers
666 c
= %w(admin
/accounts admin/users account pages
)
667 ActionController
::Routing.with_controllers c
do
668 assert_equal c
, ActionController
::Routing.possible_controllers
672 def test_normalize_unix_paths
673 load_paths
= %w(. config
/../app
/controllers config/../app//helpers script/../config/../vendor/rails
/actionpack
/lib vendor
/rails
/railties
/builtin
/rails_info app
/models lib script/../config/../foo/bar
/../../app/models
.foo
/../.bar foo
.bar
/../config
)
674 paths
= ActionController
::Routing.normalize_paths(load_paths
)
675 assert_equal
%w(vendor
/rails/railties
/builtin
/rails_info vendor
/rails
/actionpack
/lib app
/controllers app
/helpers app/models config
.bar lib
.), paths
678 def test_normalize_windows_paths
679 load_paths
= %w(. config
\\..\\app
\\controllers config
\\..\\app
\\\\helpers script
\\..\\config
\\..\\vendor
\\rails
\\actionpack
\\lib vendor
\\rails
\\railties
\\builtin
\\rails_info app
\\models lib script
\\..\\config
\\..\\foo
\\bar
\\..\\..\\app
\\models
.foo
\\..\\.bar foo
.bar
\\..\\config
)
680 paths
= ActionController
::Routing.normalize_paths(load_paths
)
681 assert_equal
%w(vendor
\\rails
\\railties
\\builtin
\\rails_info vendor
\\rails
\\actionpack
\\lib app
\\controllers app
\\helpers app
\\models config
.bar lib
.), paths
684 def test_routing_helper_module
685 assert_kind_of Module
, ActionController
::Routing::Helpers
687 h
= ActionController
::Routing::Helpers
689 assert ! c
.ancestors
.include?(h
)
690 ActionController
::Routing::Routes.install_helpers c
691 assert c
.ancestors
.include?(h
)
695 uses_mocha
'LegacyRouteSet, Route, RouteSet and RouteLoading' do
697 attr_accessor
:routes
699 def initialize(routes
)
704 only_path
= options
.delete(:only_path)
706 port
= options
.delete(:port) || 80
707 port_string
= port
== 80 ? '' : ":#{port}"
709 protocol
= options
.delete(:protocol) || "http"
710 host
= options
.delete(:host) || "named.route.test"
711 anchor
= "##{options.delete(:anchor)}" if options
.key
?(:anchor)
713 path
= routes
.generate(options
)
715 only_path
? "#{path}#{anchor}" : "#{protocol}://#{host}#{port_string}#{path}#{anchor}"
719 @request ||= MockRequest
.new(:host => "named.route.test", :method => :get)
724 attr_accessor
:path, :path_parameters, :host, :subdomains, :domain, :method
726 def initialize(values
={})
727 values
.each
{ |key
, value
| send("#{key}=", value
) }
729 subdomain
, self.domain
= values
[:host].split(/\./, 2)
730 self.subdomains
= [subdomain
]
739 (subdomains
* '.') +
'.' + domain
743 class LegacyRouteSetTests
< Test
::Unit::TestCase
747 # These tests assume optimisation is on, so re-enable it.
748 ActionController
::Base.optimise_named_routes
= true
750 @rs = ::ActionController::Routing::RouteSet.new
751 @rs.draw
{|m
| m
.connect
':controller/:action/:id' }
753 ActionController
::Routing.use_controllers!
%w(content admin
/user admin/news_feed
)
756 def test_default_setup
757 assert_equal({:controller => "content", :action => 'index'}, rs
.recognize_path("/content"))
758 assert_equal({:controller => "content", :action => 'list'}, rs
.recognize_path("/content/list"))
759 assert_equal({:controller => "content", :action => 'show', :id => '10'}, rs
.recognize_path("/content/show/10"))
761 assert_equal({:controller => "admin/user", :action => 'show', :id => '10'}, rs
.recognize_path("/admin/user/show/10"))
763 assert_equal
'/admin/user/show/10', rs
.generate(:controller => 'admin/user', :action => 'show', :id => 10)
765 assert_equal
'/admin/user/show', rs
.generate({:action => 'show'}, {:controller => 'admin/user', :action => 'list', :id => '10'})
766 assert_equal
'/admin/user/list/10', rs
.generate({}, {:controller => 'admin/user', :action => 'list', :id => '10'})
768 assert_equal
'/admin/stuff', rs
.generate({:controller => 'stuff'}, {:controller => 'admin/user', :action => 'list', :id => '10'})
769 assert_equal
'/stuff', rs
.generate({:controller => '/stuff'}, {:controller => 'admin/user', :action => 'list', :id => '10'})
772 def test_ignores_leading_slash
773 @rs.draw
{|m
| m
.connect
'/:controller/:action/:id'}
777 def test_time_recognition
778 # We create many routes to make situation more realistic
779 @rs = ::ActionController::Routing::RouteSet.new
781 map
.frontpage
'', :controller => 'search', :action => 'new'
782 map
.resources
:videos do |video
|
783 video
.resources
:comments
784 video
.resource
:file, :controller => 'video_file'
785 video
.resource
:share, :controller => 'video_shares'
786 video
.resource
:abuse, :controller => 'video_abuses'
788 map
.resources
:abuses, :controller => 'video_abuses'
789 map
.resources
:video_uploads
790 map
.resources
:video_visits
792 map
.resources
:users do |user
|
793 user
.resource
:settings
794 user
.resources
:videos
796 map
.resources
:channels do |channel
|
797 channel
.resources
:videos, :controller => 'channel_videos'
799 map
.resource
:session
800 map
.resource
:lost_password
801 map
.search
'search', :controller => 'search'
803 map
.connect
':controller/:action/:id'
808 rectime
= Benchmark
.realtime
do
810 rs
.recognize_path("/videos/1234567", {:method => :get})
811 rs
.recognize_path("/videos/1234567/abuse", {:method => :get})
812 rs
.recognize_path("/users/1234567/settings", {:method => :get})
813 rs
.recognize_path("/channels/1234567", {:method => :get})
814 rs
.recognize_path("/session/new", {:method => :get})
815 rs
.recognize_path("/admin/user/show/10", {:method => :get})
818 puts
"\n\nRecognition (#{rs.routes.size} routes):"
819 per_url
= rectime
/ (n
* 6)
820 puts
"#{per_url * 1000} ms/url"
821 puts
"#{1 / per_url} url/s\n\n"
825 def test_time_generation
830 [{:controller => 'content', :action => 'index'}, {:controller => 'content', :action => 'show'}],
831 [{:controller => 'content'}, {:controller => 'content', :action => 'index'}],
832 [{:controller => 'content', :action => 'list'}, {:controller => 'content', :action => 'index'}],
833 [{:controller => 'content', :action => 'show', :id => '10'}, {:controller => 'content', :action => 'list'}],
834 [{:controller => 'admin/user', :action => 'index'}, {:controller => 'admin/user', :action => 'show'}],
835 [{:controller => 'admin/user'}, {:controller => 'admin/user', :action => 'index'}],
836 [{:controller => 'admin/user', :action => 'list'}, {:controller => 'admin/user', :action => 'index'}],
837 [{:controller => 'admin/user', :action => 'show', :id => '10'}, {:controller => 'admin/user', :action => 'list'}],
840 gentime
= Benchmark
.realtime
do
842 pairs
.each
{|(a
, b
)| rs
.generate(a
, b
)}
846 puts
"\n\nGeneration (RouteSet): (#{(n * 8)} urls)"
847 per_url
= gentime
/ (n
* 8)
848 puts
"#{per_url * 1000} ms/url"
849 puts
"#{1 / per_url} url/s\n\n"
853 def test_route_with_colon_first
855 map
.connect
'/:controller/:action/:id', :action => 'index', :id => nil
856 map
.connect
':url', :controller => 'tiny_url', :action => 'translate'
860 def test_route_with_regexp_for_controller
862 map
.connect
':controller/:admintoken/:action/:id', :controller => /admin\
/.+/
863 map
.connect
':controller/:action/:id'
865 assert_equal({:controller => "admin/user", :admintoken => "foo", :action => "index"},
866 rs
.recognize_path("/admin/user/foo"))
867 assert_equal({:controller => "content", :action => "foo"}, rs
.recognize_path("/content/foo"))
868 assert_equal
'/admin/user/foo', rs
.generate(:controller => "admin/user", :admintoken => "foo", :action => "index")
869 assert_equal
'/content/foo', rs
.generate(:controller => "content", :action => "foo")
872 def test_route_with_regexp_and_dot
874 map
.connect
':controller/:action/:file',
875 :controller => /admin|user/,
876 :action => /upload|download/,
877 :defaults => {:file => nil},
878 :requirements => {:file => %r
{[^
/]+(\.[^/]+
)?}}
880 # Without a file extension
881 assert_equal
'/user/download/file',
882 rs
.generate(:controller => "user", :action => "download", :file => "file")
884 {:controller => "user", :action => "download", :file => "file"},
885 rs
.recognize_path("/user/download/file"))
887 # Now, let's try a file with an extension, really a dot (.)
888 assert_equal
'/user/download/file.jpg',
890 :controller => "user", :action => "download", :file => "file.jpg")
892 {:controller => "user", :action => "download", :file => "file.jpg"},
893 rs
.recognize_path("/user/download/file.jpg"))
896 def test_basic_named_route
897 rs
.add_named_route
:home, '', :controller => 'content', :action => 'list'
898 x
= setup_for_named_route
899 assert_equal("http://named.route.test/",
903 def test_basic_named_route_with_relative_url_root
904 rs
.add_named_route
:home, '', :controller => 'content', :action => 'list'
905 x
= setup_for_named_route
906 ActionController
::Base.relative_url_root
= "/foo"
907 assert_equal("http://named.route.test/foo/",
909 assert_equal
"/foo/", x
.send(:home_path)
910 ActionController
::Base.relative_url_root
= nil
913 def test_named_route_with_option
914 rs
.add_named_route
:page, 'page/:title', :controller => 'content', :action => 'show_page'
915 x
= setup_for_named_route
916 assert_equal("http://named.route.test/page/new%20stuff",
917 x
.send(:page_url, :title => 'new stuff'))
920 def test_named_route_with_default
921 rs
.add_named_route
:page, 'page/:title', :controller => 'content', :action => 'show_page', :title => 'AboutPage'
922 x
= setup_for_named_route
923 assert_equal("http://named.route.test/page/AboutRails",
924 x
.send(:page_url, :title => "AboutRails"))
928 def test_named_route_with_name_prefix
929 rs
.add_named_route
:page, 'page', :controller => 'content', :action => 'show_page', :name_prefix => 'my_'
930 x
= setup_for_named_route
931 assert_equal("http://named.route.test/page",
932 x
.send(:my_page_url))
935 def test_named_route_with_path_prefix
936 rs
.add_named_route
:page, 'page', :controller => 'content', :action => 'show_page', :path_prefix => 'my'
937 x
= setup_for_named_route
938 assert_equal("http://named.route.test/my/page",
942 def test_named_route_with_nested_controller
943 rs
.add_named_route
:users, 'admin/user', :controller => 'admin/user', :action => 'index'
944 x
= setup_for_named_route
945 assert_equal("http://named.route.test/admin/user",
949 def test_optimised_named_route_call_never_uses_url_for
950 rs
.add_named_route
:users, 'admin/user', :controller => '/admin/user', :action => 'index'
951 rs
.add_named_route
:user, 'admin/user/:id', :controller=>'/admin/user', :action=>'show'
952 x
= setup_for_named_route
953 x
.expects(:url_for).never
956 x
.send(:user_url, 2, :foo=>"bar")
957 x
.send(:user_path, 3, :bar=>"foo")
960 def test_optimised_named_route_with_host
961 rs
.add_named_route
:pages, 'pages', :controller => 'content', :action => 'show_page', :host => 'foo.com'
962 x
= setup_for_named_route
963 x
.expects(:url_for).with(:host => 'foo.com', :only_path => false, :controller => 'content', :action => 'show_page', :use_route => :pages).once
967 def setup_for_named_route
968 klass
= Class
.new(MockController
)
969 rs
.install_helpers(klass
)
973 def test_named_route_without_hash
975 map
.normal
':controller/:action/:id'
979 def test_named_route_root
981 map
.root
:controller => "hello"
983 x
= setup_for_named_route
984 assert_equal("http://named.route.test/", x
.send(:root_url))
985 assert_equal("/", x
.send(:root_path))
988 def test_named_route_with_regexps
990 map
.article
'page/:year/:month/:day/:title', :controller => 'page', :action => 'show',
991 :year => /\d+/, :month => /\d+/, :day => /\d+/
992 map
.connect
':controller/:action/:id'
994 x
= setup_for_named_route
996 # {:controller => 'page', :action => 'show', :title => 'hi', :use_route => :article, :only_path => false},
997 # x.send(:article_url, :title => 'hi')
1000 "http://named.route.test/page/2005/6/10/hi",
1001 x
.send(:article_url, :title => 'hi', :day => 10, :year => 2005, :month => 6)
1005 def test_changing_controller
1006 assert_equal
'/admin/stuff/show/10', rs
.generate(
1007 {:controller => 'stuff', :action => 'show', :id => 10},
1008 {:controller => 'admin/user', :action => 'index'}
1012 def test_paths_escaped
1014 map
.path
'file/*path', :controller => 'content', :action => 'show_file'
1015 map
.connect
':controller/:action/:id'
1018 # No + to space in URI escaping, only for query params.
1019 results
= rs
.recognize_path
"/file/hello+world
/how+are+you
%3F
"
1020 assert results, "Recognition should have succeeded
"
1021 assert_equal ['hello+world
', 'how+are+you
?'], results[:path]
1023 # Use %20 for space instead.
1024 results = rs.recognize_path "/file/hello%20world/how%20are%20you%3F"
1025 assert results, "Recognition should have succeeded"
1026 assert_equal ['hello world
', 'how are you
?'], results[:path]
1028 results = rs.recognize_path "/file"
1029 assert results, "Recognition should have succeeded"
1030 assert_equal [], results[:path]
1033 def test_paths_slashes_unescaped_with_ordered_parameters
1034 rs.add_named_route :path, '/file/*path
', :controller => 'content
'
1036 # No / to %2F in URI, only for query params.
1037 x = setup_for_named_route
1038 assert_equal("/file/hello/world", x.send(:path_path, 'hello
/world
'))
1041 def test_non_controllers_cannot_be_matched
1043 map.connect ':controller/:action/:id'
1045 assert_raises(ActionController::RoutingError) { rs.recognize_path("/not_a/show/10") }
1048 def test_paths_do_not_accept_defaults
1049 assert_raises(ActionController::RoutingError) do
1051 map.path 'file
/*path
', :controller => 'content
', :action => 'show_file
', :path => %w(fake default)
1052 map.connect ':controller/:action/:id'
1057 map.path 'file
/*path
', :controller => 'content
', :action => 'show_file
', :path => []
1058 map.connect ':controller/:action/:id'
1062 def test_should_list_options_diff_when_routing_requirements_dont_match
1064 map.post 'post
/:id', :controller=> 'post', :action=> 'show', :requirements => {:id => /\d+
/}
1066 exception
= assert_raise(ActionController
::RoutingError) { rs
.generate(:controller => 'post', :action => 'show', :bad_param => "foo", :use_route => "post") }
1067 assert_match
/^post_url failed to generate/, exception
.message
1068 from_match
= exception
.message
.match(/from \{[^\}]+\}/).to_s
1069 assert_match
/:bad_param=>"foo"/, from_match
1070 assert_match
/:action=>"show"/, from_match
1071 assert_match
/:controller=>"post"/, from_match
1073 expected_match
= exception
.message
.match(/expected: \{[^\}]+\}/).to_s
1074 assert_no_match
/:bad_param=>"foo"/, expected_match
1075 assert_match
/:action=>"show"/, expected_match
1076 assert_match
/:controller=>"post"/, expected_match
1078 diff_match
= exception
.message
.match(/diff: \{[^\}]+\}/).to_s
1079 assert_match
/:bad_param=>"foo"/, diff_match
1080 assert_no_match
/:action=>"show"/, diff_match
1081 assert_no_match
/:controller=>"post"/, diff_match
1084 # this specifies the case where your formerly would get a very confusing error message with an empty diff
1085 def test_should_have_better_error_message_when_options_diff_is_empty
1087 map
.content
'/content/:query', :controller => 'content', :action => 'show'
1090 exception
= assert_raise(ActionController
::RoutingError) { rs
.generate(:controller => 'content', :action => 'show', :use_route => "content") }
1091 assert_match
%r
[:action=>"show"], exception
.message
1092 assert_match
%r
[:controller=>"content"], exception
.message
1093 assert_match
%r
[you may have ambiguous routes
, or you may need to supply additional parameters
for this route
], exception
.message
1094 assert_match
%r
[content_url has the following required parameters
: \
["content", :query\
] - are they all satisfied
?], exception
.message
1097 def test_dynamic_path_allowed
1099 map
.connect
'*path', :controller => 'content', :action => 'show_file'
1102 assert_equal
'/pages/boo', rs
.generate(:controller => 'content', :action => 'show_file', :path => %w(pages boo
))
1105 def test_dynamic_recall_paths_allowed
1107 map
.connect
'*path', :controller => 'content', :action => 'show_file'
1110 recall_path
= ActionController
::Routing::PathSegment::Result.new(%w(pages boo
))
1111 assert_equal
'/pages/boo', rs
.generate({}, :controller => 'content', :action => 'show_file', :path => recall_path
)
1116 map
.connect
'page/:id/:action', :controller => 'pages', :action => 'show'
1117 map
.connect
':controller/:action/:id'
1120 assert_equal
'/page/20', rs
.generate({:id => 20}, {:controller => 'pages', :action => 'show'})
1121 assert_equal
'/page/20', rs
.generate(:controller => 'pages', :id => 20, :action => 'show')
1122 assert_equal
'/pages/boo', rs
.generate(:controller => 'pages', :action => 'boo')
1125 def test_route_with_fixnum_default
1127 map
.connect
'page/:id', :controller => 'content', :action => 'show_page', :id => 1
1128 map
.connect
':controller/:action/:id'
1131 assert_equal
'/page', rs
.generate(:controller => 'content', :action => 'show_page')
1132 assert_equal
'/page', rs
.generate(:controller => 'content', :action => 'show_page', :id => 1)
1133 assert_equal
'/page', rs
.generate(:controller => 'content', :action => 'show_page', :id => '1')
1134 assert_equal
'/page/10', rs
.generate(:controller => 'content', :action => 'show_page', :id => 10)
1136 assert_equal({:controller => "content", :action => 'show_page', :id => '1'}, rs
.recognize_path("/page"))
1137 assert_equal({:controller => "content", :action => 'show_page', :id => '1'}, rs
.recognize_path("/page/1"))
1138 assert_equal({:controller => "content", :action => 'show_page', :id => '10'}, rs
.recognize_path("/page/10"))
1141 # For newer revision
1142 def test_route_with_text_default
1144 map
.connect
'page/:id', :controller => 'content', :action => 'show_page', :id => 1
1145 map
.connect
':controller/:action/:id'
1148 assert_equal
'/page/foo', rs
.generate(:controller => 'content', :action => 'show_page', :id => 'foo')
1149 assert_equal({:controller => "content", :action => 'show_page', :id => 'foo'}, rs
.recognize_path("/page/foo"))
1151 token
= "\321\202\320\265\320\272\321\201\321\202" # 'text' in russian
1152 escaped_token
= CGI
::escape(token
)
1154 assert_equal
'/page/' + escaped_token
, rs
.generate(:controller => 'content', :action => 'show_page', :id => token
)
1155 assert_equal({:controller => "content", :action => 'show_page', :id => token
}, rs
.recognize_path("/page/#{escaped_token}"))
1158 def test_action_expiry
1159 assert_equal
'/content', rs
.generate({:controller => 'content'}, {:controller => 'content', :action => 'show'})
1162 def test_recognition_with_uppercase_controller_name
1163 assert_equal({:controller => "content", :action => 'index'}, rs
.recognize_path("/Content"))
1164 assert_equal({:controller => "content", :action => 'list'}, rs
.recognize_path("/ConTent/list"))
1165 assert_equal({:controller => "content", :action => 'show', :id => '10'}, rs
.recognize_path("/CONTENT/show/10"))
1167 # these used to work, before the routes rewrite, but support for this was pulled in the new version...
1168 #assert_equal({'controller' => "admin/news_feed", 'action' => 'index'}, rs.recognize_path("Admin/NewsFeed"))
1169 #assert_equal({'controller' => "admin/news_feed", 'action' => 'index'}, rs.recognize_path("Admin/News_Feed"))
1172 def test_requirement_should_prevent_optional_id
1174 map
.post
'post/:id', :controller=> 'post', :action=> 'show', :requirements => {:id => /\d+
/}
1177 assert_equal
'/post/10', rs
.generate(:controller => 'post', :action => 'show', :id => 10)
1179 assert_raises ActionController
::RoutingError do
1180 rs
.generate(:controller => 'post', :action => 'show')
1184 def test_both_requirement_and_optional
1186 map
.blog('test/:year', :controller => 'post', :action => 'show',
1187 :defaults => { :year => nil },
1188 :requirements => { :year => /\d{4}/ }
1190 map
.connect
':controller/:action/:id'
1193 assert_equal
'/test', rs
.generate(:controller => 'post', :action => 'show')
1194 assert_equal
'/test', rs
.generate(:controller => 'post', :action => 'show', :year => nil)
1196 x
= setup_for_named_route
1197 assert_equal("http://named.route.test/test",
1201 def test_set_to_nil_forgets
1203 map
.connect
'pages/:year/:month/:day', :controller => 'content', :action => 'list_pages', :month => nil, :day => nil
1204 map
.connect
':controller/:action/:id'
1207 assert_equal
'/pages/2005',
1208 rs
.generate(:controller => 'content', :action => 'list_pages', :year => 2005)
1209 assert_equal
'/pages/2005/6',
1210 rs
.generate(:controller => 'content', :action => 'list_pages', :year => 2005, :month => 6)
1211 assert_equal
'/pages/2005/6/12',
1212 rs
.generate(:controller => 'content', :action => 'list_pages', :year => 2005, :month => 6, :day => 12)
1214 assert_equal
'/pages/2005/6/4',
1215 rs
.generate({:day => 4}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'})
1217 assert_equal
'/pages/2005/6',
1218 rs
.generate({:day => nil}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'})
1220 assert_equal
'/pages/2005',
1221 rs
.generate({:day => nil, :month => nil}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'})
1224 def test_url_with_no_action_specified
1226 map
.connect
'', :controller => 'content'
1227 map
.connect
':controller/:action/:id'
1230 assert_equal
'/', rs
.generate(:controller => 'content', :action => 'index')
1231 assert_equal
'/', rs
.generate(:controller => 'content')
1234 def test_named_url_with_no_action_specified
1236 map
.home
'', :controller => 'content'
1237 map
.connect
':controller/:action/:id'
1240 assert_equal
'/', rs
.generate(:controller => 'content', :action => 'index')
1241 assert_equal
'/', rs
.generate(:controller => 'content')
1243 x
= setup_for_named_route
1244 assert_equal("http://named.route.test/",
1248 def test_url_generated_when_forgetting_action
1249 [{:controller => 'content', :action => 'index'}, {:controller => 'content'}].each
do |hash
|
1252 map
.connect
':controller/:action/:id'
1254 assert_equal
'/', rs
.generate({:action => nil}, {:controller => 'content', :action => 'hello'})
1255 assert_equal
'/', rs
.generate({:controller => 'content'})
1256 assert_equal
'/content/hi', rs
.generate({:controller => 'content', :action => 'hi'})
1260 def test_named_route_method
1262 map
.categories
'categories', :controller => 'content', :action => 'categories'
1263 map
.connect
':controller/:action/:id'
1266 assert_equal
'/categories', rs
.generate(:controller => 'content', :action => 'categories')
1267 assert_equal
'/content/hi', rs
.generate({:controller => 'content', :action => 'hi'})
1270 def test_named_routes_array
1271 test_named_route_method
1272 assert_equal
[:categories], rs
.named_routes
.names
1275 def test_nil_defaults
1277 map
.connect
'journal',
1278 :controller => 'content',
1279 :action => 'list_journal',
1280 :date => nil, :user_id => nil
1281 map
.connect
':controller/:action/:id'
1284 assert_equal
'/journal', rs
.generate(:controller => 'content', :action => 'list_journal', :date => nil, :user_id => nil)
1287 def setup_request_method_routes_for(method
)
1288 @request = ActionController
::TestRequest.new
1289 @request.env["REQUEST_METHOD"] = method
1290 @request.request_uri
= "/match"
1293 r
.connect
'/match', :controller => 'books', :action => 'get', :conditions => { :method => :get }
1294 r
.connect
'/match', :controller => 'books', :action => 'post', :conditions => { :method => :post }
1295 r
.connect
'/match', :controller => 'books', :action => 'put', :conditions => { :method => :put }
1296 r
.connect
'/match', :controller => 'books', :action => 'delete', :conditions => { :method => :delete }
1300 %w(GET POST PUT DELETE
).each
do |request_method
|
1301 define_method("test_request_method_recognized_with_#{request_method}") do
1303 Object
.const_set(:BooksController, Class
.new(ActionController
::Base))
1305 setup_request_method_routes_for(request_method
)
1307 assert_nothing_raised
{ rs
.recognize(@request) }
1308 assert_equal request_method
.downcase
, @request.path_parameters
[:action]
1310 Object
.send(:remove_const, :BooksController) rescue nil
1315 def test_recognize_array_of_methods
1316 Object
.const_set(:BooksController, Class
.new(ActionController
::Base))
1318 r
.connect
'/match', :controller => 'books', :action => 'get_or_post', :conditions => { :method => [:get, :post] }
1319 r
.connect
'/match', :controller => 'books', :action => 'not_get_or_post'
1322 @request = ActionController
::TestRequest.new
1323 @request.env["REQUEST_METHOD"] = 'POST'
1324 @request.request_uri
= "/match"
1325 assert_nothing_raised
{ rs
.recognize(@request) }
1326 assert_equal
'get_or_post', @request.path_parameters
[:action]
1328 # have to recreate or else the RouteSet uses a cached version:
1329 @request = ActionController
::TestRequest.new
1330 @request.env["REQUEST_METHOD"] = 'PUT'
1331 @request.request_uri
= "/match"
1332 assert_nothing_raised
{ rs
.recognize(@request) }
1333 assert_equal
'not_get_or_post', @request.path_parameters
[:action]
1335 Object
.send(:remove_const, :BooksController) rescue nil
1338 def test_subpath_recognized
1339 Object
.const_set(:SubpathBooksController, Class
.new(ActionController
::Base))
1342 r
.connect
'/books/:id/edit', :controller => 'subpath_books', :action => 'edit'
1343 r
.connect
'/items/:id/:action', :controller => 'subpath_books'
1344 r
.connect
'/posts/new/:action', :controller => 'subpath_books'
1345 r
.connect
'/posts/:id', :controller => 'subpath_books', :action => "show"
1348 hash
= rs
.recognize_path
"/books/17/edit"
1350 assert_equal
%w(subpath_books
17 edit
), [hash
[:controller], hash
[:id], hash
[:action]]
1352 hash
= rs
.recognize_path
"/items/3/complete"
1354 assert_equal
%w(subpath_books
3 complete
), [hash
[:controller], hash
[:id], hash
[:action]]
1356 hash
= rs
.recognize_path
"/posts/new/preview"
1358 assert_equal
%w(subpath_books preview
), [hash
[:controller], hash
[:action]]
1360 hash
= rs
.recognize_path
"/posts/7"
1362 assert_equal
%w(subpath_books show
7), [hash
[:controller], hash
[:action], hash
[:id]]
1364 Object
.send(:remove_const, :SubpathBooksController) rescue nil
1367 def test_subpath_generated
1368 Object
.const_set(:SubpathBooksController, Class
.new(ActionController
::Base))
1371 r
.connect
'/books/:id/edit', :controller => 'subpath_books', :action => 'edit'
1372 r
.connect
'/items/:id/:action', :controller => 'subpath_books'
1373 r
.connect
'/posts/new/:action', :controller => 'subpath_books'
1376 assert_equal
"/books/7/edit", rs
.generate(:controller => "subpath_books", :id => 7, :action => "edit")
1377 assert_equal
"/items/15/complete", rs
.generate(:controller => "subpath_books", :id => 15, :action => "complete")
1378 assert_equal
"/posts/new/preview", rs
.generate(:controller => "subpath_books", :action => "preview")
1380 Object
.send(:remove_const, :SubpathBooksController) rescue nil
1383 def test_failed_requirements_raises_exception_with_violated_requirements
1385 r
.foo_with_requirement
'foos/:id', :controller=>'foos', :requirements=>{:id=>/\d+
/}
1388 x
= setup_for_named_route
1389 assert_raises(ActionController
::RoutingError) do
1390 x
.send(:foo_with_requirement_url, "I am Against the requirements")
1394 def test_routes_changed_correctly_after_clear
1395 ActionController
::Base.optimise_named_routes
= true
1396 rs
= ::ActionController::Routing::RouteSet.new
1398 r
.connect
'ca', :controller => 'ca', :action => "aa"
1399 r
.connect
'cb', :controller => 'cb', :action => "ab"
1400 r
.connect
'cc', :controller => 'cc', :action => "ac"
1401 r
.connect
':controller/:action/:id'
1402 r
.connect
':controller/:action/:id.:format'
1405 hash
= rs
.recognize_path
"/cc"
1408 assert_equal
%w(cc ac
), [hash
[:controller], hash
[:action]]
1411 r
.connect
'cb', :controller => 'cb', :action => "ab"
1412 r
.connect
'cc', :controller => 'cc', :action => "ac"
1413 r
.connect
':controller/:action/:id'
1414 r
.connect
':controller/:action/:id.:format'
1417 hash
= rs
.recognize_path
"/cc"
1420 assert_equal
%w(cc ac
), [hash
[:controller], hash
[:action]]
1425 class RouteTest
< Test
::Unit::TestCase
1427 @route = ROUTING
::Route.new
1430 def slash_segment(is_optional
= false)
1431 ROUTING
::DividerSegment.new('/', :optional => is_optional
)
1435 unless defined?(@default_route)
1437 segments
<< ROUTING
::StaticSegment.new('/', :raw => true)
1438 segments
<< ROUTING
::DynamicSegment.new(:controller)
1439 segments
<< slash_segment(:optional)
1440 segments
<< ROUTING
::DynamicSegment.new(:action, :default => 'index', :optional => true)
1441 segments
<< slash_segment(:optional)
1442 segments
<< ROUTING
::DynamicSegment.new(:id, :optional => true)
1443 segments
<< slash_segment(:optional)
1444 @default_route = ROUTING
::Route.new(segments
).freeze
1449 def test_default_route_recognition
1450 expected
= {:controller => 'accounts', :action => 'show', :id => '10'}
1451 assert_equal expected
, default_route
.recognize('/accounts/show/10')
1452 assert_equal expected
, default_route
.recognize('/accounts/show/10/')
1454 expected
[:id] = 'jamis'
1455 assert_equal expected
, default_route
.recognize('/accounts/show/jamis/')
1458 assert_equal expected
, default_route
.recognize('/accounts/show')
1459 assert_equal expected
, default_route
.recognize('/accounts/show/')
1461 expected
[:action] = 'index'
1462 assert_equal expected
, default_route
.recognize('/accounts/')
1463 assert_equal expected
, default_route
.recognize('/accounts')
1465 assert_equal
nil, default_route
.recognize('/')
1466 assert_equal
nil, default_route
.recognize('/accounts/how/goood/it/is/to/be/free')
1469 def test_default_route_should_omit_default_action
1470 o
= {:controller => 'accounts', :action => 'index'}
1471 assert_equal
'/accounts', default_route
.generate(o
, o
, {})
1474 def test_default_route_should_include_default_action_when_id_present
1475 o
= {:controller => 'accounts', :action => 'index', :id => '20'}
1476 assert_equal
'/accounts/index/20', default_route
.generate(o
, o
, {})
1479 def test_default_route_should_work_with_action_but_no_id
1480 o
= {:controller => 'accounts', :action => 'list_all'}
1481 assert_equal
'/accounts/list_all', default_route
.generate(o
, o
, {})
1484 def test_default_route_should_uri_escape_pluses
1485 expected
= { :controller => 'accounts', :action => 'show', :id => 'hello world' }
1486 assert_equal expected
, default_route
.recognize('/accounts/show/hello world')
1487 assert_equal expected
, default_route
.recognize('/accounts/show/hello%20world')
1488 assert_equal
'/accounts/show/hello%20world', default_route
.generate(expected
, expected
, {})
1490 expected
[:id] = 'hello+world
'
1491 assert_equal expected, default_route.recognize('/accounts/show
/hello+world
')
1492 assert_equal expected, default_route.recognize('/accounts/show
/hello
%2Bworld
')
1493 assert_equal '/accounts/show
/hello+world
', default_route.generate(expected, expected, {})
1496 def test_matches_controller_and_action
1497 # requirement_for should only be called for the action and controller _once_
1498 @route.expects(:requirement_for).with(:controller).times(1).returns('pages
')
1499 @route.expects(:requirement_for).with(:action).times(1).returns('show
')
1501 @route.requirements = {:controller => 'pages
', :action => 'show
'}
1502 assert @route.matches_controller_and_action?('pages
', 'show
')
1503 assert !@route.matches_controller_and_action
?('not_pages', 'show')
1504 assert !
@route.matches_controller_and_action
?('pages', 'not_show')
1507 def test_parameter_shell
1508 page_url
= ROUTING
::Route.new
1509 page_url
.requirements
= {:controller => 'pages', :action => 'show', :id => /\d+/}
1510 assert_equal({:controller => 'pages', :action => 'show'}, page_url
.parameter_shell
)
1514 route
= ROUTING
::RouteBuilder.new
.build
'/users/:id.:format', :controller => "users", :action => "show", :format => "html"
1516 { :controller => "users", :action => "show", :format => "html" },
1520 def test_builder_complains_without_controller
1521 assert_raises(ArgumentError
) do
1522 ROUTING
::RouteBuilder.new
.build
'/contact', :contoller => "contact", :action => "index"
1526 def test_significant_keys_for_default_route
1527 keys
= default_route
.significant_keys
.sort_by
{|k
| k
.to_s
}
1528 assert_equal
[:action, :controller, :id], keys
1531 def test_significant_keys
1533 segments
<< ROUTING
::StaticSegment.new('/', :raw => true)
1534 segments
<< ROUTING
::StaticSegment.new('user')
1535 segments
<< ROUTING
::StaticSegment.new('/', :raw => true, :optional => true)
1536 segments
<< ROUTING
::DynamicSegment.new(:user)
1537 segments
<< ROUTING
::StaticSegment.new('/', :raw => true, :optional => true)
1539 requirements
= {:controller => 'users', :action => 'show'}
1541 user_url
= ROUTING
::Route.new(segments
, requirements
)
1542 keys
= user_url
.significant_keys
.sort_by
{ |k
| k
.to_s
}
1543 assert_equal
[:action, :controller, :user], keys
1546 def test_build_empty_query_string
1547 assert_equal
'', @route.build_query_string({})
1550 def test_build_query_string_with_nil_value
1551 assert_equal
'', @route.build_query_string({:x => nil})
1554 def test_simple_build_query_string
1555 assert_equal
'?x=1&y=2', order_query_string(@route.build_query_string(:x => '1', :y => '2'))
1558 def test_convert_ints_build_query_string
1559 assert_equal
'?x=1&y=2', order_query_string(@route.build_query_string(:x => 1, :y => 2))
1562 def test_escape_spaces_build_query_string
1563 assert_equal
'?x=hello+world
&y
=goodbye+world
', order_query_string(@route.build_query_string(:x => 'hello world
', :y => 'goodbye world
'))
1566 def test_expand_array_build_query_string
1567 assert_equal '?x
%5B
%5D
=1&x
%5B
%5D
=2', order_query_string(@route.build_query_string(:x => [1, 2]))
1570 def test_escape_spaces_build_query_string_selected_keys
1571 assert_equal '?x
=hello+world
', order_query_string(@route.build_query_string({:x => 'hello world
', :y => 'goodbye world
'}, [:x]))
1575 def order_query_string(qs)
1576 '?' + qs
[1..-1].split('&').sort
.join('&')
1580 class RouteSetTest
< Test
::Unit::TestCase
1582 @set ||= ROUTING
::RouteSet.new
1586 @request ||= MockRequest
.new(:host => "named.routes.test", :method => :get)
1589 def test_generate_extras
1590 set
.draw
{ |m
| m
.connect
':controller/:action/:id' }
1591 path
, extras
= set
.generate_extras(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
1592 assert_equal
"/foo/bar/15", path
1593 assert_equal
%w(that this
), extras
.map(&:to_s).sort
1597 set
.draw
{ |m
| m
.connect
':controller/:action/:id' }
1598 extras
= set
.extra_keys(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
1599 assert_equal
%w(that this
), extras
.map(&:to_s).sort
1602 def test_generate_extras_not_first
1604 map
.connect
':controller/:action/:id.:format'
1605 map
.connect
':controller/:action/:id'
1607 path
, extras
= set
.generate_extras(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
1608 assert_equal
"/foo/bar/15", path
1609 assert_equal
%w(that this
), extras
.map(&:to_s).sort
1612 def test_generate_not_first
1614 map
.connect
':controller/:action/:id.:format'
1615 map
.connect
':controller/:action/:id'
1617 assert_equal
"/foo/bar/15?this=hello", set
.generate(:controller => "foo", :action => "bar", :id => 15, :this => "hello")
1620 def test_extra_keys_not_first
1622 map
.connect
':controller/:action/:id.:format'
1623 map
.connect
':controller/:action/:id'
1625 extras
= set
.extra_keys(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
1626 assert_equal
%w(that this
), extras
.map(&:to_s).sort
1630 assert_equal
0, set
.routes
.size
1632 map
.connect
'/hello/world', :controller => 'a', :action => 'b'
1634 assert_equal
1, set
.routes
.size
1638 assert_equal
0, set
.routes
.size
1640 map
.hello
'/hello/world', :controller => 'a', :action => 'b'
1642 assert_equal
1, set
.routes
.size
1643 assert_equal set
.routes
.first
, set
.named_routes
[:hello]
1646 def test_later_named_routes_take_precedence
1648 map
.hello
'/hello/world', :controller => 'a', :action => 'b'
1649 map
.hello
'/hello', :controller => 'a', :action => 'b'
1651 assert_equal set
.routes
.last
, set
.named_routes
[:hello]
1654 def setup_named_route_test
1656 map
.show
'/people/:id', :controller => 'people', :action => 'show'
1657 map
.index
'/people', :controller => 'people', :action => 'index'
1658 map
.multi
'/people/go/:foo/:bar/joe/:id', :controller => 'people', :action => 'multi'
1659 map
.users
'/admin/users', :controller => 'admin/users', :action => 'index'
1662 klass
= Class
.new(MockController
)
1663 set
.install_helpers(klass
)
1667 def test_named_route_hash_access_method
1668 controller
= setup_named_route_test
1671 { :controller => 'people', :action => 'show', :id => 5, :use_route => :show, :only_path => false },
1672 controller
.send(:hash_for_show_url, :id => 5))
1675 { :controller => 'people', :action => 'index', :use_route => :index, :only_path => false },
1676 controller
.send(:hash_for_index_url))
1679 { :controller => 'people', :action => 'show', :id => 5, :use_route => :show, :only_path => true },
1680 controller
.send(:hash_for_show_path, :id => 5)
1684 def test_named_route_url_method
1685 controller
= setup_named_route_test
1687 assert_equal
"http://named.route.test/people/5", controller
.send(:show_url, :id => 5)
1688 assert_equal
"/people/5", controller
.send(:show_path, :id => 5)
1690 assert_equal
"http://named.route.test/people", controller
.send(:index_url)
1691 assert_equal
"/people", controller
.send(:index_path)
1693 assert_equal
"http://named.route.test/admin/users", controller
.send(:users_url)
1694 assert_equal
'/admin/users', controller
.send(:users_path)
1695 assert_equal
'/admin/users', set
.generate(controller
.send(:hash_for_users_url), {:controller => 'users', :action => 'index'})
1698 def test_named_route_url_method_with_anchor
1699 controller
= setup_named_route_test
1701 assert_equal
"http://named.route.test/people/5#location", controller
.send(:show_url, :id => 5, :anchor => 'location')
1702 assert_equal
"/people/5#location", controller
.send(:show_path, :id => 5, :anchor => 'location')
1704 assert_equal
"http://named.route.test/people#location", controller
.send(:index_url, :anchor => 'location')
1705 assert_equal
"/people#location", controller
.send(:index_path, :anchor => 'location')
1707 assert_equal
"http://named.route.test/admin/users#location", controller
.send(:users_url, :anchor => 'location')
1708 assert_equal
'/admin/users#location', controller
.send(:users_path, :anchor => 'location')
1710 assert_equal
"http://named.route.test/people/go/7/hello/joe/5#location",
1711 controller
.send(:multi_url, 7, "hello", 5, :anchor => 'location')
1713 assert_equal
"http://named.route.test/people/go/7/hello/joe/5?baz=bar#location",
1714 controller
.send(:multi_url, 7, "hello", 5, :baz => "bar", :anchor => 'location')
1716 assert_equal
"http://named.route.test/people?baz=bar#location",
1717 controller
.send(:index_url, :baz => "bar", :anchor => 'location')
1720 def test_named_route_url_method_with_port
1721 controller
= setup_named_route_test
1722 assert_equal
"http://named.route.test:8080/people/5", controller
.send(:show_url, 5, :port=>8080)
1725 def test_named_route_url_method_with_host
1726 controller
= setup_named_route_test
1727 assert_equal
"http://some.example.com/people/5", controller
.send(:show_url, 5, :host=>"some.example.com")
1730 def test_named_route_url_method_with_protocol
1731 controller
= setup_named_route_test
1732 assert_equal
"https://named.route.test/people/5", controller
.send(:show_url, 5, :protocol => "https")
1735 def test_named_route_url_method_with_ordered_parameters
1736 controller
= setup_named_route_test
1737 assert_equal
"http://named.route.test/people/go/7/hello/joe/5",
1738 controller
.send(:multi_url, 7, "hello", 5)
1741 def test_named_route_url_method_with_ordered_parameters_and_hash
1742 controller
= setup_named_route_test
1743 assert_equal
"http://named.route.test/people/go/7/hello/joe/5?baz=bar",
1744 controller
.send(:multi_url, 7, "hello", 5, :baz => "bar")
1747 def test_named_route_url_method_with_ordered_parameters_and_empty_hash
1748 controller
= setup_named_route_test
1749 assert_equal
"http://named.route.test/people/go/7/hello/joe/5",
1750 controller
.send(:multi_url, 7, "hello", 5, {})
1753 def test_named_route_url_method_with_no_positional_arguments
1754 controller
= setup_named_route_test
1755 assert_equal
"http://named.route.test/people?baz=bar",
1756 controller
.send(:index_url, :baz => "bar")
1759 def test_draw_default_route
1760 ActionController
::Routing.with_controllers(['users']) do
1762 map
.connect
'/:controller/:action/:id'
1765 assert_equal
1, set
.routes
.size
1766 route
= set
.routes
.first
1768 assert route
.segments
.last
.optional
?
1770 assert_equal
'/users/show/10', set
.generate(:controller => 'users', :action => 'show', :id => 10)
1771 assert_equal
'/users/index/10', set
.generate(:controller => 'users', :id => 10)
1773 assert_equal({:controller => 'users', :action => 'index', :id => '10'}, set
.recognize_path('/users/index/10'))
1774 assert_equal({:controller => 'users', :action => 'index', :id => '10'}, set
.recognize_path('/users/index/10/'))
1778 def test_draw_default_route_with_default_controller
1779 ActionController
::Routing.with_controllers(['users']) do
1781 map
.connect
'/:controller/:action/:id', :controller => 'users'
1783 assert_equal({:controller => 'users', :action => 'index'}, set
.recognize_path('/'))
1787 def test_route_with_parameter_shell
1788 ActionController
::Routing.with_controllers(['users', 'pages']) do
1790 map
.connect
'page/:id', :controller => 'pages', :action => 'show', :id => /\d+
/
1791 map
.connect
'/:controller/:action/:id'
1794 assert_equal({:controller => 'pages', :action => 'index'}, set
.recognize_path('/pages'))
1795 assert_equal({:controller => 'pages', :action => 'index'}, set
.recognize_path('/pages/index'))
1796 assert_equal({:controller => 'pages', :action => 'list'}, set
.recognize_path('/pages/list'))
1798 assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set
.recognize_path('/pages/show/10'))
1799 assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set
.recognize_path('/page/10'))
1803 def test_route_requirements_with_anchor_chars_are_invalid
1804 assert_raises ArgumentError
do
1806 map
.connect
'page/:id', :controller => 'pages', :action => 'show', :id => /^\d+
/
1809 assert_raises ArgumentError
do
1811 map
.connect
'page/:id', :controller => 'pages', :action => 'show', :id => /\A\d+
/
1814 assert_raises ArgumentError
do
1816 map
.connect
'page/:id', :controller => 'pages', :action => 'show', :id => /\d+
$/
1819 assert_raises ArgumentError
do
1821 map
.connect
'page/:id', :controller => 'pages', :action => 'show', :id => /\d+\Z
/
1824 assert_raises ArgumentError
do
1826 map
.connect
'page/:id', :controller => 'pages', :action => 'show', :id => /\d+\z
/
1829 assert_nothing_raised
do
1831 map
.connect
'page/:id', :controller => 'pages', :action => 'show', :id => /\d+
/, :name => /^
(david
|jamis
)/
1833 assert_raises ActionController
::RoutingError do
1834 set
.generate
:controller => 'pages', :action => 'show', :id => 10
1839 def test_route_requirements_with_invalid_http_method_is_invalid
1840 assert_raises ArgumentError
do
1842 map
.connect
'valid/route', :controller => 'pages', :action => 'show', :conditions => {:method => :invalid}
1847 def test_route_requirements_with_head_method_condition_is_invalid
1848 assert_raises ArgumentError
do
1850 map
.connect
'valid/route', :controller => 'pages', :action => 'show', :conditions => {:method => :head}
1855 def test_non_path_route_requirements_match_all
1857 map
.connect
'page/37s', :controller => 'pages', :action => 'show', :name => /(jamis
|david
)/
1859 assert_equal
'/page/37s', set
.generate(:controller => 'pages', :action => 'show', :name => 'jamis')
1860 assert_raises ActionController
::RoutingError do
1861 set
.generate(:controller => 'pages', :action => 'show', :name => 'not_jamis')
1863 assert_raises ActionController
::RoutingError do
1864 set
.generate(:controller => 'pages', :action => 'show', :name => 'nor_jamis_and_david')
1868 def test_recognize_with_encoded_id_and_regex
1870 map
.connect
'page/:id', :controller => 'pages', :action => 'show', :id => /[a-zA-Z0-9\+
]+
/
1873 assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set
.recognize_path('/page/10'))
1874 assert_equal({:controller => 'pages', :action => 'show', :id => 'hello+world
'}, set.recognize_path('/page/hello+world
'))
1877 def test_recognize_with_conditions
1878 Object.const_set(:PeopleController, Class.new)
1881 map.with_options(:controller => "people") do |people|
1882 people.people "/people", :action => "index", :conditions => { :method => :get }
1883 people.connect "/people", :action => "create", :conditions => { :method => :post }
1884 people.person "/people/:id", :action => "show", :conditions => { :method => :get }
1885 people.connect "/people/:id", :action => "update", :conditions => { :method => :put }
1886 people.connect "/people/:id", :action => "destroy", :conditions => { :method => :delete }
1890 request.path = "/people"
1891 request.method = :get
1892 assert_nothing_raised { set.recognize(request) }
1893 assert_equal("index", request.path_parameters[:action])
1895 request.method = :post
1896 assert_nothing_raised { set.recognize(request) }
1897 assert_equal("create", request.path_parameters[:action])
1899 request.method = :put
1900 assert_nothing_raised { set.recognize(request) }
1901 assert_equal("update", request.path_parameters[:action])
1904 request.method = :bacon
1905 set.recognize(request)
1906 flunk 'Should have raised NotImplemented
'
1907 rescue ActionController::NotImplemented => e
1908 assert_equal [:get, :post, :put, :delete], e.allowed_methods
1911 request.path = "/people/5"
1912 request.method = :get
1913 assert_nothing_raised { set.recognize(request) }
1914 assert_equal("show", request.path_parameters[:action])
1915 assert_equal("5", request.path_parameters[:id])
1917 request.method = :put
1918 assert_nothing_raised { set.recognize(request) }
1919 assert_equal("update", request.path_parameters[:action])
1920 assert_equal("5", request.path_parameters[:id])
1922 request.method = :delete
1923 assert_nothing_raised { set.recognize(request) }
1924 assert_equal("destroy", request.path_parameters[:action])
1925 assert_equal("5", request.path_parameters[:id])
1928 request.method = :post
1929 set.recognize(request)
1930 flunk 'Should have raised MethodNotAllowed
'
1931 rescue ActionController::MethodNotAllowed => e
1932 assert_equal [:get, :put, :delete], e.allowed_methods
1936 Object.send(:remove_const, :PeopleController)
1939 def test_recognize_with_alias_in_conditions
1940 Object.const_set(:PeopleController, Class.new)
1943 map.people "/people", :controller => 'people
', :action => "index",
1944 :conditions => { :method => :get }
1948 request.path = "/people"
1949 request.method = :get
1950 assert_nothing_raised { set.recognize(request) }
1951 assert_equal("people", request.path_parameters[:controller])
1952 assert_equal("index", request.path_parameters[:action])
1955 request.method = :get
1956 assert_nothing_raised { set.recognize(request) }
1957 assert_equal("people", request.path_parameters[:controller])
1958 assert_equal("index", request.path_parameters[:action])
1960 Object.send(:remove_const, :PeopleController)
1963 def test_typo_recognition
1964 Object.const_set(:ArticlesController, Class.new)
1967 map.connect 'articles
/:year/:month/:day/:title',
1968 :controller => 'articles
', :action => 'permalink
',
1969 :year => /\d{4}/, :day => /\d{1,2}/, :month => /\d{1,2}/
1972 request.path = "/articles/2005/11/05/a-very-interesting-article"
1973 request.method = :get
1974 assert_nothing_raised { set.recognize(request) }
1975 assert_equal("permalink", request.path_parameters[:action])
1976 assert_equal("2005", request.path_parameters[:year])
1977 assert_equal("11", request.path_parameters[:month])
1978 assert_equal("05", request.path_parameters[:day])
1979 assert_equal("a-very-interesting-article", request.path_parameters[:title])
1982 Object.send(:remove_const, :ArticlesController)
1985 def test_routing_traversal_does_not_load_extra_classes
1986 assert !Object
.const_defined
?("Profiler__"), "Profiler should not be loaded"
1988 map
.connect
'/profile', :controller => 'profile'
1991 request
.path
= '/profile'
1993 set
.recognize(request
) rescue nil
1995 assert !Object
.const_defined
?("Profiler__"), "Profiler should not be loaded"
1998 def test_recognize_with_conditions_and_format
1999 Object
.const_set(:PeopleController, Class
.new
)
2002 map
.with_options(:controller => "people") do |people
|
2003 people
.person
"/people/:id", :action => "show", :conditions => { :method => :get }
2004 people
.connect
"/people/:id", :action => "update", :conditions => { :method => :put }
2005 people
.connect
"/people/:id.:_format", :action => "show", :conditions => { :method => :get }
2009 request
.path
= "/people/5"
2010 request
.method
= :get
2011 assert_nothing_raised
{ set
.recognize(request
) }
2012 assert_equal("show", request
.path_parameters
[:action])
2013 assert_equal("5", request
.path_parameters
[:id])
2015 request
.method
= :put
2016 assert_nothing_raised
{ set
.recognize(request
) }
2017 assert_equal("update", request
.path_parameters
[:action])
2019 request
.path
= "/people/5.png"
2020 request
.method
= :get
2021 assert_nothing_raised
{ set
.recognize(request
) }
2022 assert_equal("show", request
.path_parameters
[:action])
2023 assert_equal("5", request
.path_parameters
[:id])
2024 assert_equal("png", request
.path_parameters
[:_format])
2026 Object
.send(:remove_const, :PeopleController)
2029 def test_generate_with_default_action
2031 map
.connect
"/people", :controller => "people"
2032 map
.connect
"/people/list", :controller => "people", :action => "list"
2035 url
= set
.generate(:controller => "people", :action => "list")
2036 assert_equal
"/people/list", url
2040 Object
.const_set(:PeopleController, Class
.new
)
2042 set
.draw
{ |map
| map
.root
:controller => "people" }
2045 request
.method
= :get
2046 assert_nothing_raised
{ set
.recognize(request
) }
2047 assert_equal("people", request
.path_parameters
[:controller])
2048 assert_equal("index", request
.path_parameters
[:action])
2050 Object
.send(:remove_const, :PeopleController)
2054 Object
.const_set(:Api, Module
.new
{ |m
| m
.const_set(:ProductsController, Class
.new
) })
2058 map
.namespace
'api' do |api
|
2059 api
.route
'inventory', :controller => "products", :action => 'inventory'
2064 request
.path
= "/api/inventory"
2065 request
.method
= :get
2066 assert_nothing_raised
{ set
.recognize(request
) }
2067 assert_equal("api/products", request
.path_parameters
[:controller])
2068 assert_equal("inventory", request
.path_parameters
[:action])
2070 Object
.send(:remove_const, :Api)
2073 def test_namespaced_root_map
2074 Object
.const_set(:Api, Module
.new
{ |m
| m
.const_set(:ProductsController, Class
.new
) })
2078 map
.namespace
'api' do |api
|
2079 api
.root
:controller => "products"
2084 request
.path
= "/api"
2085 request
.method
= :get
2086 assert_nothing_raised
{ set
.recognize(request
) }
2087 assert_equal("api/products", request
.path_parameters
[:controller])
2088 assert_equal("index", request
.path_parameters
[:action])
2090 Object
.send(:remove_const, :Api)
2093 def test_namespace_with_path_prefix
2094 Object
.const_set(:Api, Module
.new
{ |m
| m
.const_set(:ProductsController, Class
.new
) })
2098 map
.namespace
'api', :path_prefix => 'prefix' do |api
|
2099 api
.route
'inventory', :controller => "products", :action => 'inventory'
2104 request
.path
= "/prefix/inventory"
2105 request
.method
= :get
2106 assert_nothing_raised
{ set
.recognize(request
) }
2107 assert_equal("api/products", request
.path_parameters
[:controller])
2108 assert_equal("inventory", request
.path_parameters
[:action])
2110 Object
.send(:remove_const, :Api)
2113 def test_generate_finds_best_fit
2115 map
.connect
"/people", :controller => "people", :action => "index"
2116 map
.connect
"/ws/people", :controller => "people", :action => "index", :ws => true
2119 url
= set
.generate(:controller => "people", :action => "index", :ws => true)
2120 assert_equal
"/ws/people", url
2123 def test_generate_changes_controller_module
2124 set
.draw
{ |map
| map
.connect
':controller/:action/:id' }
2125 current
= { :controller => "bling/bloop", :action => "bap", :id => 9 }
2126 url
= set
.generate({:controller => "foo/bar", :action => "baz", :id => 7}, current
)
2127 assert_equal
"/foo/bar/baz/7", url
2130 def test_id_is_not_impossibly_sticky
2132 map
.connect
'foo/:number', :controller => "people", :action => "index"
2133 map
.connect
':controller/:action/:id'
2136 url
= set
.generate({:controller => "people", :action => "index", :number => 3},
2137 {:controller => "people", :action => "index", :id => "21"})
2138 assert_equal
"/foo/3", url
2141 def test_id_is_sticky_when_it_ought_to_be
2143 map
.connect
':controller/:id/:action'
2146 url
= set
.generate({:action => "destroy"}, {:controller => "people", :action => "show", :id => "7"})
2147 assert_equal
"/people/7/destroy", url
2150 def test_use_static_path_when_possible
2152 map
.connect
'about', :controller => "welcome", :action => "about"
2153 map
.connect
':controller/:action/:id'
2156 url
= set
.generate({:controller => "welcome", :action => "about"},
2157 {:controller => "welcome", :action => "get", :id => "7"})
2158 assert_equal
"/about", url
2162 set
.draw
{ |map
| map
.connect
':controller/:action/:id' }
2164 args
= { :controller => "foo", :action => "bar", :id => "7", :x => "y" }
2165 assert_equal
"/foo/bar/7?x=y", set
.generate(args
)
2166 assert_equal
["/foo/bar/7", [:x]], set
.generate_extras(args
)
2167 assert_equal
[:x], set
.extra_keys(args
)
2170 def test_generate_with_path_prefix
2171 set
.draw
{ |map
| map
.connect
':controller/:action/:id', :path_prefix => 'my' }
2173 args
= { :controller => "foo", :action => "bar", :id => "7", :x => "y" }
2174 assert_equal
"/my/foo/bar/7?x=y", set
.generate(args
)
2177 def test_named_routes_are_never_relative_to_modules
2179 map
.connect
"/connection/manage/:action", :controller => 'connection/manage'
2180 map
.connect
"/connection/connection", :controller => "connection/connection"
2181 map
.family_connection
"/connection", :controller => "connection"
2184 url
= set
.generate({:controller => "connection"}, {:controller => 'connection/manage'})
2185 assert_equal
"/connection/connection", url
2187 url
= set
.generate({:use_route => :family_connection, :controller => "connection"}, {:controller => 'connection/manage'})
2188 assert_equal
"/connection", url
2191 def test_action_left_off_when_id_is_recalled
2193 map
.connect
':controller/:action/:id'
2195 assert_equal
'/post', set
.generate(
2196 {:controller => 'post', :action => 'index'},
2197 {:controller => 'post', :action => 'show', :id => '10'}
2201 def test_query_params_will_be_shown_when_recalled
2203 map
.connect
'show_post/:parameter', :controller => 'post', :action => 'show'
2204 map
.connect
':controller/:action/:id'
2206 assert_equal
'/post/edit?parameter=1', set
.generate(
2207 {:action => 'edit', :parameter => 1},
2208 {:controller => 'post', :action => 'show', :parameter => 1}
2212 def test_expiry_determination_should_consider_values_with_to_param
2213 set
.draw
{ |map
| map
.connect
'projects/:project_id/:controller/:action' }
2214 assert_equal
'/projects/1/post/show', set
.generate(
2215 {:action => 'show', :project_id => 1},
2216 {:controller => 'post', :action => 'show', :project_id => '1'})
2219 def test_generate_all
2221 map
.connect
'show_post/:id', :controller => 'post', :action => 'show'
2222 map
.connect
':controller/:action/:id'
2225 {:action => 'show', :id => 10, :generate_all => true},
2226 {:controller => 'post', :action => 'show'}
2228 assert_equal
2, all
.length
2229 assert_equal
'/show_post/10', all
.first
2230 assert_equal
'/post/show/10', all
.last
2233 def test_named_route_in_nested_resource
2235 map
.resources
:projects do |project
|
2236 project
.milestones
'milestones', :controller => 'milestones', :action => 'index'
2240 request
.path
= "/projects/1/milestones"
2241 request
.method
= :get
2242 assert_nothing_raised
{ set
.recognize(request
) }
2243 assert_equal("milestones", request
.path_parameters
[:controller])
2244 assert_equal("index", request
.path_parameters
[:action])
2247 def test_setting_root_in_namespace_using_symbol
2248 assert_nothing_raised
do
2250 map
.namespace
:admin do |admin
|
2251 admin
.root
:controller => 'home'
2257 def test_setting_root_in_namespace_using_string
2258 assert_nothing_raised
do
2260 map
.namespace
'admin' do |admin
|
2261 admin
.root
:controller => 'home'
2267 def test_route_requirements_with_unsupported_regexp_options_must_error
2268 assert_raises ArgumentError
do
2270 map
.connect
'page/:name', :controller => 'pages',
2272 :requirements => {:name => /(david|jamis)/m
}
2277 def test_route_requirements_with_supported_options_must_not_error
2278 assert_nothing_raised
do
2280 map
.connect
'page/:name', :controller => 'pages',
2282 :requirements => {:name => /(david|jamis)/i
}
2285 assert_nothing_raised
do
2287 map
.connect
'page/:name', :controller => 'pages',
2289 :requirements => {:name => / # Desperately overcommented regexp
2299 def test_route_requirement_recognize_with_ignore_case
2301 map
.connect
'page/:name', :controller => 'pages',
2303 :requirements => {:name => /(david|jamis)/i
}
2305 assert_equal({:controller => 'pages', :action => 'show', :name => 'jamis'}, set
.recognize_path('/page/jamis'))
2306 assert_raises ActionController
::RoutingError do
2307 set
.recognize_path('/page/davidjamis')
2309 assert_equal({:controller => 'pages', :action => 'show', :name => 'DAVID'}, set
.recognize_path('/page/DAVID'))
2312 def test_route_requirement_generate_with_ignore_case
2314 map
.connect
'page/:name', :controller => 'pages',
2316 :requirements => {:name => /(david|jamis)/i
}
2318 url
= set
.generate({:controller => 'pages', :action => 'show', :name => 'david'})
2319 assert_equal
"/page/david", url
2320 assert_raises ActionController
::RoutingError do
2321 url
= set
.generate({:controller => 'pages', :action => 'show', :name => 'davidjamis'})
2323 url
= set
.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'})
2324 assert_equal
"/page/JAMIS", url
2327 def test_route_requirement_recognize_with_extended_syntax
2329 map
.connect
'page/:name', :controller => 'pages',
2331 :requirements => {:name => / # Desperately overcommented regexp
2338 assert_equal({:controller => 'pages', :action => 'show', :name => 'jamis'}, set
.recognize_path('/page/jamis'))
2339 assert_equal({:controller => 'pages', :action => 'show', :name => 'david'}, set
.recognize_path('/page/david'))
2340 assert_raises ActionController
::RoutingError do
2341 set
.recognize_path('/page/david #The Creator')
2343 assert_raises ActionController
::RoutingError do
2344 set
.recognize_path('/page/David')
2348 def test_route_requirement_generate_with_extended_syntax
2350 map
.connect
'page/:name', :controller => 'pages',
2352 :requirements => {:name => / # Desperately overcommented regexp
2359 url
= set
.generate({:controller => 'pages', :action => 'show', :name => 'david'})
2360 assert_equal
"/page/david", url
2361 assert_raises ActionController
::RoutingError do
2362 url
= set
.generate({:controller => 'pages', :action => 'show', :name => 'davidjamis'})
2364 assert_raises ActionController
::RoutingError do
2365 url
= set
.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'})
2369 def test_route_requirement_generate_with_xi_modifiers
2371 map
.connect
'page/:name', :controller => 'pages',
2373 :requirements => {:name => / # Desperately overcommented regexp
2380 url
= set
.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'})
2381 assert_equal
"/page/JAMIS", url
2384 def test_route_requirement_recognize_with_xi_modifiers
2386 map
.connect
'page/:name', :controller => 'pages',
2388 :requirements => {:name => / # Desperately overcommented regexp
2395 assert_equal({:controller => 'pages', :action => 'show', :name => 'JAMIS'}, set
.recognize_path('/page/JAMIS'))
2399 class RouteLoadingTest
< Test
::Unit::TestCase
2401 routes
.instance_variable_set
'@routes_last_modified', nil
2402 silence_warnings
{ Object
.const_set
:RAILS_ROOT, '.' }
2403 ActionController
::Routing::Routes.configuration_file
= File
.join(RAILS_ROOT
, 'config', 'routes.rb')
2405 @stat = stub_everything
2409 ActionController
::Routing::Routes.configuration_file
= nil
2410 Object
.send
:remove_const, :RAILS_ROOT
2414 File
.expects(:stat).returns(@stat)
2415 routes
.expects(:load).with(regexp_matches(/routes\.rb$/))
2420 def test_no_reload_when_not_modified
2421 @stat.expects(:mtime).times(2).returns(1)
2422 File
.expects(:stat).times(2).returns(@stat)
2423 routes
.expects(:load).with(regexp_matches(/routes\.rb$/)).at_most_once
2425 2.times
{ routes
.reload
}
2428 def test_reload_when_modified
2429 @stat.expects(:mtime).at_least(2).returns(1, 2)
2430 File
.expects(:stat).at_least(2).returns(@stat)
2431 routes
.expects(:load).with(regexp_matches(/routes\.rb$/)).times(2)
2433 2.times
{ routes
.reload
}
2436 def test_bang_forces_reload
2437 @stat.expects(:mtime).at_least(2).returns(1)
2438 File
.expects(:stat).at_least(2).returns(@stat)
2439 routes
.expects(:load).with(regexp_matches(/routes\.rb$/)).times(2)
2441 2.times
{ routes
.reload!
}
2444 def test_adding_inflections_forces_reload
2445 ActiveSupport
::Inflector::Inflections.instance
.expects(:uncountable).with('equipment')
2446 routes
.expects(:reload!
)
2448 ActiveSupport
::Inflector.inflections
{ |inflect
| inflect
.uncountable('equipment') }
2451 def test_load_with_configuration
2452 routes
.configuration_file
= "foobarbaz"
2453 File
.expects(:stat).returns(@stat)
2454 routes
.expects(:load).with("foobarbaz")
2461 ActionController
::Routing::Routes