ef5611975154f19c8c4a913f4427342f26468660
[feedcatcher.git] / vendor / rails / actionpack / test / controller / routing_test.rb
1 require 'abstract_unit'
2 require 'controller/fake_controllers'
3
4 class MilestonesController < ActionController::Base
5 def index() head :ok end
6 alias_method :show, :index
7 def rescue_action(e) raise e end
8 end
9
10 RunTimeTests = ARGV.include? 'time'
11 ROUTING = ActionController::Routing
12
13 class ROUTING::RouteBuilder
14 attr_reader :warn_output
15
16 def warn(msg)
17 (@warn_output ||= []) << msg
18 end
19 end
20
21 # See RFC 3986, section 3.3 for allowed path characters.
22 class UriReservedCharactersRoutingTest < Test::Unit::TestCase
23 def setup
24 ActionController::Routing.use_controllers! ['controller']
25 @set = ActionController::Routing::RouteSet.new
26 @set.draw do |map|
27 map.connect ':controller/:action/:variable/*additional'
28 end
29
30 safe, unsafe = %w(: @ & = + $ , ;), %w(^ / ? # [ ])
31 hex = unsafe.map { |char| '%' + char.unpack('H2').first.upcase }
32
33 @segment = "#{safe.join}#{unsafe.join}".freeze
34 @escaped = "#{safe.join}#{hex.join}".freeze
35 end
36
37 def test_route_generation_escapes_unsafe_path_characters
38 assert_equal "/contr#{@segment}oller/act#{@escaped}ion/var#{@escaped}iable/add#{@escaped}itional-1/add#{@escaped}itional-2",
39 @set.generate(:controller => "contr#{@segment}oller",
40 :action => "act#{@segment}ion",
41 :variable => "var#{@segment}iable",
42 :additional => ["add#{@segment}itional-1", "add#{@segment}itional-2"])
43 end
44
45 def test_route_recognition_unescapes_path_components
46 options = { :controller => "controller",
47 :action => "act#{@segment}ion",
48 :variable => "var#{@segment}iable",
49 :additional => ["add#{@segment}itional-1", "add#{@segment}itional-2"] }
50 assert_equal options, @set.recognize_path("/controller/act#{@escaped}ion/var#{@escaped}iable/add#{@escaped}itional-1/add#{@escaped}itional-2")
51 end
52
53 def test_route_generation_allows_passing_non_string_values_to_generated_helper
54 assert_equal "/controller/action/variable/1/2", @set.generate(:controller => "controller",
55 :action => "action",
56 :variable => "variable",
57 :additional => [1, 2])
58 end
59 end
60
61 class SegmentTest < Test::Unit::TestCase
62 def test_first_segment_should_interpolate_for_structure
63 s = ROUTING::Segment.new
64 def s.interpolation_statement(array) 'hello' end
65 assert_equal 'hello', s.continue_string_structure([])
66 end
67
68 def test_interpolation_statement
69 s = ROUTING::StaticSegment.new("Hello")
70 assert_equal "Hello", eval(s.interpolation_statement([]))
71 assert_equal "HelloHello", eval(s.interpolation_statement([s]))
72
73 s2 = ROUTING::StaticSegment.new("-")
74 assert_equal "Hello-Hello", eval(s.interpolation_statement([s, s2]))
75
76 s3 = ROUTING::StaticSegment.new("World")
77 assert_equal "Hello-World", eval(s3.interpolation_statement([s, s2]))
78 end
79 end
80
81 class StaticSegmentTest < Test::Unit::TestCase
82 def test_interpolation_chunk_should_respect_raw
83 s = ROUTING::StaticSegment.new('Hello World')
84 assert !s.raw?
85 assert_equal 'Hello%20World', s.interpolation_chunk
86
87 s = ROUTING::StaticSegment.new('Hello World', :raw => true)
88 assert s.raw?
89 assert_equal 'Hello World', s.interpolation_chunk
90 end
91
92 def test_regexp_chunk_should_escape_specials
93 s = ROUTING::StaticSegment.new('Hello*World')
94 assert_equal 'Hello\*World', s.regexp_chunk
95
96 s = ROUTING::StaticSegment.new('HelloWorld')
97 assert_equal 'HelloWorld', s.regexp_chunk
98 end
99
100 def test_regexp_chunk_should_add_question_mark_for_optionals
101 s = ROUTING::StaticSegment.new("/", :optional => true)
102 assert_equal "/?", s.regexp_chunk
103
104 s = ROUTING::StaticSegment.new("hello", :optional => true)
105 assert_equal "(?:hello)?", s.regexp_chunk
106 end
107 end
108
109 class DynamicSegmentTest < Test::Unit::TestCase
110 def segment(options = {})
111 unless @segment
112 @segment = ROUTING::DynamicSegment.new(:a, options)
113 end
114 @segment
115 end
116
117 def test_extract_value
118 s = ROUTING::DynamicSegment.new(:a)
119
120 hash = {:a => '10', :b => '20'}
121 assert_equal '10', eval(s.extract_value)
122
123 hash = {:b => '20'}
124 assert_equal nil, eval(s.extract_value)
125
126 s.default = '20'
127 assert_equal '20', eval(s.extract_value)
128 end
129
130 def test_default_local_name
131 assert_equal 'a_value', segment.local_name,
132 "Unexpected name -- all value_check tests will fail!"
133 end
134
135 def test_presence_value_check
136 a_value = 10
137 assert eval(segment.value_check)
138 end
139
140 def test_regexp_value_check_rejects_nil
141 segment = segment(:regexp => /\d+/)
142
143 a_value = nil
144 assert !eval(segment.value_check)
145 end
146
147 def test_optional_regexp_value_check_should_accept_nil
148 segment = segment(:regexp => /\d+/, :optional => true)
149
150 a_value = nil
151 assert eval(segment.value_check)
152 end
153
154 def test_regexp_value_check_rejects_no_match
155 segment = segment(:regexp => /\d+/)
156
157 a_value = "Hello20World"
158 assert !eval(segment.value_check)
159
160 a_value = "20Hi"
161 assert !eval(segment.value_check)
162 end
163
164 def test_regexp_value_check_accepts_match
165 segment = segment(:regexp => /\d+/)
166 a_value = "30"
167 assert eval(segment.value_check)
168 end
169
170 def test_value_check_fails_on_nil
171 a_value = nil
172 assert ! eval(segment.value_check)
173 end
174
175 def test_optional_value_needs_no_check
176 segment = segment(:optional => true)
177
178 a_value = nil
179 assert_equal nil, segment.value_check
180 end
181
182 def test_regexp_value_check_should_accept_match_with_default
183 segment = segment(:regexp => /\d+/, :default => '200')
184
185 a_value = '100'
186 assert eval(segment.value_check)
187 end
188
189 def test_expiry_should_not_trigger_once_expired
190 expired = true
191 hash = merged = {:a => 2, :b => 3}
192 options = {:b => 3}
193 expire_on = Hash.new { raise 'No!!!' }
194
195 eval(segment.expiry_statement)
196 rescue RuntimeError
197 flunk "Expiry check should not have occurred!"
198 end
199
200 def test_expiry_should_occur_according_to_expire_on
201 expired = false
202 hash = merged = {:a => 2, :b => 3}
203 options = {:b => 3}
204
205 expire_on = {:b => true, :a => false}
206 eval(segment.expiry_statement)
207 assert !expired
208 assert_equal({:a => 2, :b => 3}, hash)
209
210 expire_on = {:b => true, :a => true}
211 eval(segment.expiry_statement)
212 assert expired
213 assert_equal({:b => 3}, hash)
214 end
215
216 def test_extraction_code_should_return_on_nil
217 hash = merged = {:b => 3}
218 options = {:b => 3}
219 a_value = nil
220
221 # Local jump because of return inside eval.
222 assert_raise(LocalJumpError) { eval(segment.extraction_code) }
223 end
224
225 def test_extraction_code_should_return_on_mismatch
226 segment = segment(:regexp => /\d+/)
227 hash = merged = {:a => 'Hi', :b => '3'}
228 options = {:b => '3'}
229 a_value = nil
230
231 # Local jump because of return inside eval.
232 assert_raise(LocalJumpError) { eval(segment.extraction_code) }
233 end
234
235 def test_extraction_code_should_accept_value_and_set_local
236 hash = merged = {:a => 'Hi', :b => '3'}
237 options = {:b => '3'}
238 a_value = nil
239 expired = true
240
241 eval(segment.extraction_code)
242 assert_equal 'Hi', a_value
243 end
244
245 def test_extraction_should_work_without_value_check
246 segment.default = 'hi'
247 hash = merged = {:b => '3'}
248 options = {:b => '3'}
249 a_value = nil
250 expired = true
251
252 eval(segment.extraction_code)
253 assert_equal 'hi', a_value
254 end
255
256 def test_extraction_code_should_perform_expiry
257 expired = false
258 hash = merged = {:a => 'Hi', :b => '3'}
259 options = {:b => '3'}
260 expire_on = {:a => true}
261 a_value = nil
262
263 eval(segment.extraction_code)
264 assert_equal 'Hi', a_value
265 assert expired
266 assert_equal options, hash
267 end
268
269 def test_interpolation_chunk_should_replace_value
270 a_value = 'Hi'
271 assert_equal a_value, eval(%("#{segment.interpolation_chunk}"))
272 end
273
274 def test_interpolation_chunk_should_accept_nil
275 a_value = nil
276 assert_equal '', eval(%("#{segment.interpolation_chunk('a_value')}"))
277 end
278
279 def test_value_regexp_should_be_nil_without_regexp
280 assert_equal nil, segment.value_regexp
281 end
282
283 def test_value_regexp_should_match_exacly
284 segment = segment(:regexp => /\d+/)
285 assert_no_match segment.value_regexp, "Hello 10 World"
286 assert_no_match segment.value_regexp, "Hello 10"
287 assert_no_match segment.value_regexp, "10 World"
288 assert_match segment.value_regexp, "10"
289 end
290
291 def test_regexp_chunk_should_return_string
292 segment = segment(:regexp => /\d+/)
293 assert_kind_of String, segment.regexp_chunk
294 end
295
296 def test_build_pattern_non_optional_with_no_captures
297 # Non optional
298 a_segment = ROUTING::DynamicSegment.new(nil, :regexp => /\d+/)
299 assert_equal "(\\d+)stuff", a_segment.build_pattern('stuff')
300 end
301
302 def test_build_pattern_non_optional_with_captures
303 # Non optional
304 a_segment = ROUTING::DynamicSegment.new(nil, :regexp => /(\d+)(.*?)/)
305 assert_equal "((\\d+)(.*?))stuff", a_segment.build_pattern('stuff')
306 end
307
308 def test_optionality_implied
309 a_segment = ROUTING::DynamicSegment.new(:id)
310 assert a_segment.optionality_implied?
311
312 a_segment = ROUTING::DynamicSegment.new(:action)
313 assert a_segment.optionality_implied?
314 end
315
316 def test_modifiers_must_be_handled_sensibly
317 a_segment = ROUTING::DynamicSegment.new(nil, :regexp => /david|jamis/i)
318 assert_equal "((?i-mx:david|jamis))stuff", a_segment.build_pattern('stuff')
319 a_segment = ROUTING::DynamicSegment.new(nil, :regexp => /david|jamis/x)
320 assert_equal "((?x-mi:david|jamis))stuff", a_segment.build_pattern('stuff')
321 a_segment = ROUTING::DynamicSegment.new(nil, :regexp => /david|jamis/)
322 assert_equal "(david|jamis)stuff", a_segment.build_pattern('stuff')
323 end
324 end
325
326 class ControllerSegmentTest < Test::Unit::TestCase
327 def test_regexp_should_only_match_possible_controllers
328 ActionController::Routing.with_controllers %w(admin/accounts admin/users account pages) do
329 cs = ROUTING::ControllerSegment.new :controller
330 regexp = %r{\A#{cs.regexp_chunk}\Z}
331
332 ActionController::Routing.possible_controllers.each do |name|
333 assert_match regexp, name
334 assert_no_match regexp, "#{name}_fake"
335
336 match = regexp.match name
337 assert_equal name, match[1]
338 end
339 end
340 end
341 end
342
343 class PathSegmentTest < Test::Unit::TestCase
344 def segment(options = {})
345 unless @segment
346 @segment = ROUTING::PathSegment.new(:path, options)
347 end
348 @segment
349 end
350
351 def test_regexp_chunk_should_return_string
352 segment = segment(:regexp => /[a-z]+/)
353 assert_kind_of String, segment.regexp_chunk
354 end
355
356 def test_regexp_chunk_should_be_wrapped_with_parenthesis
357 segment = segment(:regexp => /[a-z]+/)
358 assert_equal "([a-z]+)", segment.regexp_chunk
359 end
360
361 def test_regexp_chunk_should_respect_options
362 segment = segment(:regexp => /[a-z]+/i)
363 assert_equal "((?i-mx:[a-z]+))", segment.regexp_chunk
364 end
365 end
366
367 class RouteBuilderTest < Test::Unit::TestCase
368 def builder
369 @builder ||= ROUTING::RouteBuilder.new
370 end
371
372 def build(path, options)
373 builder.build(path, options)
374 end
375
376 def test_options_should_not_be_modified
377 requirements1 = { :id => /\w+/, :controller => /(?:[a-z](?:-?[a-z]+)*)/ }
378 requirements2 = requirements1.dup
379
380 assert_equal requirements1, requirements2
381
382 with_options(:controller => 'folder',
383 :requirements => requirements2) do |m|
384 m.build 'folders/new', :action => 'new'
385 end
386
387 assert_equal requirements1, requirements2
388 end
389
390 def test_segment_for_static
391 segment, rest = builder.segment_for 'ulysses'
392 assert_equal '', rest
393 assert_kind_of ROUTING::StaticSegment, segment
394 assert_equal 'ulysses', segment.value
395 end
396
397 def test_segment_for_action
398 segment, rest = builder.segment_for ':action'
399 assert_equal '', rest
400 assert_kind_of ROUTING::DynamicSegment, segment
401 assert_equal :action, segment.key
402 assert_equal 'index', segment.default
403 end
404
405 def test_segment_for_dynamic
406 segment, rest = builder.segment_for ':login'
407 assert_equal '', rest
408 assert_kind_of ROUTING::DynamicSegment, segment
409 assert_equal :login, segment.key
410 assert_equal nil, segment.default
411 assert ! segment.optional?
412 end
413
414 def test_segment_for_with_rest
415 segment, rest = builder.segment_for ':login/:action'
416 assert_equal :login, segment.key
417 assert_equal '/:action', rest
418 segment, rest = builder.segment_for rest
419 assert_equal '/', segment.value
420 assert_equal ':action', rest
421 segment, rest = builder.segment_for rest
422 assert_equal :action, segment.key
423 assert_equal '', rest
424 end
425
426 def test_segments_for
427 segments = builder.segments_for_route_path '/:controller/:action/:id'
428
429 assert_kind_of ROUTING::DividerSegment, segments[0]
430 assert_equal '/', segments[2].value
431
432 assert_kind_of ROUTING::DynamicSegment, segments[1]
433 assert_equal :controller, segments[1].key
434
435 assert_kind_of ROUTING::DividerSegment, segments[2]
436 assert_equal '/', segments[2].value
437
438 assert_kind_of ROUTING::DynamicSegment, segments[3]
439 assert_equal :action, segments[3].key
440
441 assert_kind_of ROUTING::DividerSegment, segments[4]
442 assert_equal '/', segments[4].value
443
444 assert_kind_of ROUTING::DynamicSegment, segments[5]
445 assert_equal :id, segments[5].key
446 end
447
448 def test_segment_for_action
449 s, r = builder.segment_for(':action/something/else')
450 assert_equal '/something/else', r
451 assert_equal :action, s.key
452 end
453
454 def test_action_default_should_not_trigger_on_prefix
455 s, r = builder.segment_for ':action_name/something/else'
456 assert_equal '/something/else', r
457 assert_equal :action_name, s.key
458 assert_equal nil, s.default
459 end
460
461 def test_divide_route_options
462 segments = builder.segments_for_route_path '/cars/:action/:person/:car/'
463 defaults, requirements = builder.divide_route_options(segments,
464 :action => 'buy', :person => /\w+/, :car => /\w+/,
465 :defaults => {:person => nil, :car => nil}
466 )
467
468 assert_equal({:action => 'buy', :person => nil, :car => nil}, defaults)
469 assert_equal({:person => /\w+/, :car => /\w+/}, requirements)
470 end
471
472 def test_assign_route_options
473 segments = builder.segments_for_route_path '/cars/:action/:person/:car/'
474 defaults = {:action => 'buy', :person => nil, :car => nil}
475 requirements = {:person => /\w+/, :car => /\w+/}
476
477 route_requirements = builder.assign_route_options(segments, defaults, requirements)
478 assert_equal({}, route_requirements)
479
480 assert_equal :action, segments[3].key
481 assert_equal 'buy', segments[3].default
482
483 assert_equal :person, segments[5].key
484 assert_equal %r/\w+/, segments[5].regexp
485 assert segments[5].optional?
486
487 assert_equal :car, segments[7].key
488 assert_equal %r/\w+/, segments[7].regexp
489 assert segments[7].optional?
490 end
491
492 def test_assign_route_options_with_anchor_chars
493 segments = builder.segments_for_route_path '/cars/:action/:person/:car/'
494 defaults = {:action => 'buy', :person => nil, :car => nil}
495 requirements = {:person => /\w+/, :car => /^\w+$/}
496
497 assert_raise ArgumentError do
498 route_requirements = builder.assign_route_options(segments, defaults, requirements)
499 end
500
501 requirements[:car] = /[^\/]+/
502 route_requirements = builder.assign_route_options(segments, defaults, requirements)
503 end
504
505 def test_optional_segments_preceding_required_segments
506 segments = builder.segments_for_route_path '/cars/:action/:person/:car/'
507 defaults = {:action => 'buy', :person => nil, :car => "model-t"}
508 assert builder.assign_route_options(segments, defaults, {}).empty?
509
510 0.upto(1) { |i| assert !segments[i].optional?, "segment #{i} is optional and it shouldn't be" }
511 assert segments[2].optional?
512
513 assert_equal nil, builder.warn_output # should only warn on the :person segment
514 end
515
516 def test_segmentation_of_dot_path
517 segments = builder.segments_for_route_path '/books/:action.rss'
518 assert builder.assign_route_options(segments, {}, {}).empty?
519 assert_equal 6, segments.length # "/", "books", "/", ":action", ".", "rss"
520 assert !segments.any? { |seg| seg.optional? }
521 end
522
523 def test_segmentation_of_dynamic_dot_path
524 segments = builder.segments_for_route_path '/books/:action.:format'
525 assert builder.assign_route_options(segments, {}, {}).empty?
526 assert_equal 6, segments.length # "/", "books", "/", ":action", ".", ":format"
527 assert !segments.any? { |seg| seg.optional? }
528 assert_kind_of ROUTING::DynamicSegment, segments.last
529 end
530
531 def test_assignment_of_default_options
532 segments = builder.segments_for_route_path '/:controller/:action/:id/'
533 action, id = segments[-4], segments[-2]
534
535 assert_equal :action, action.key
536 assert_equal :id, id.key
537 assert ! action.optional?
538 assert ! id.optional?
539
540 builder.assign_default_route_options(segments)
541
542 assert_equal 'index', action.default
543 assert action.optional?
544 assert id.optional?
545 end
546
547 def test_assignment_of_default_options_respects_existing_defaults
548 segments = builder.segments_for_route_path '/:controller/:action/:id/'
549 action, id = segments[-4], segments[-2]
550
551 assert_equal :action, action.key
552 assert_equal :id, id.key
553 action.default = 'show'
554 action.is_optional = true
555
556 id.default = 'Welcome'
557 id.is_optional = true
558
559 builder.assign_default_route_options(segments)
560
561 assert_equal 'show', action.default
562 assert action.optional?
563 assert_equal 'Welcome', id.default
564 assert id.optional?
565 end
566
567 def test_assignment_of_default_options_respects_regexps
568 segments = builder.segments_for_route_path '/:controller/:action/:id/'
569 action = segments[-4]
570
571 assert_equal :action, action.key
572 segments[-4] = ROUTING::DynamicSegment.new(:action, :regexp => /show|in/)
573
574 builder.assign_default_route_options(segments)
575
576 assert_equal nil, action.default
577 assert ! action.optional?
578 end
579
580 def test_assignment_of_is_optional_when_default
581 segments = builder.segments_for_route_path '/books/:action.rss'
582 assert_equal segments[3].key, :action
583 segments[3].default = 'changes'
584 builder.ensure_required_segments(segments)
585 assert ! segments[3].optional?
586 end
587
588 def test_is_optional_is_assigned_to_default_segments
589 segments = builder.segments_for_route_path '/books/:action'
590 builder.assign_route_options(segments, {:action => 'index'}, {})
591
592 assert_equal segments[3].key, :action
593 assert segments[3].optional?
594 assert_kind_of ROUTING::DividerSegment, segments[2]
595 assert segments[2].optional?
596 end
597
598 # XXX is optional not being set right?
599 # /blah/:defaulted_segment <-- is the second slash optional? it should be.
600
601 def test_route_build
602 ActionController::Routing.with_controllers %w(users pages) do
603 r = builder.build '/:controller/:action/:id/', :action => nil
604
605 [0, 2, 4].each do |i|
606 assert_kind_of ROUTING::DividerSegment, r.segments[i]
607 assert_equal '/', r.segments[i].value
608 assert r.segments[i].optional? if i > 1
609 end
610
611 assert_kind_of ROUTING::DynamicSegment, r.segments[1]
612 assert_equal :controller, r.segments[1].key
613 assert_equal nil, r.segments[1].default
614
615 assert_kind_of ROUTING::DynamicSegment, r.segments[3]
616 assert_equal :action, r.segments[3].key
617 assert_equal 'index', r.segments[3].default
618
619 assert_kind_of ROUTING::DynamicSegment, r.segments[5]
620 assert_equal :id, r.segments[5].key
621 assert r.segments[5].optional?
622 end
623 end
624
625 def test_slashes_are_implied
626 routes = [
627 builder.build('/:controller/:action/:id/', :action => nil),
628 builder.build('/:controller/:action/:id', :action => nil),
629 builder.build(':controller/:action/:id', :action => nil),
630 builder.build('/:controller/:action/:id/', :action => nil)
631 ]
632 expected = routes.first.segments.length
633 routes.each_with_index do |route, i|
634 found = route.segments.length
635 assert_equal expected, found, "Route #{i + 1} has #{found} segments, expected #{expected}"
636 end
637 end
638 end
639
640 class RoutingTest < Test::Unit::TestCase
641 def test_possible_controllers
642 true_controller_paths = ActionController::Routing.controller_paths
643
644 ActionController::Routing.use_controllers! nil
645
646 silence_warnings do
647 Object.send(:const_set, :RAILS_ROOT, File.dirname(__FILE__) + '/controller_fixtures')
648 end
649
650 ActionController::Routing.controller_paths = [
651 RAILS_ROOT, RAILS_ROOT + '/app/controllers', RAILS_ROOT + '/vendor/plugins/bad_plugin/lib'
652 ]
653
654 assert_equal ["admin/user", "plugin", "user"], ActionController::Routing.possible_controllers.sort
655 ensure
656 if true_controller_paths
657 ActionController::Routing.controller_paths = true_controller_paths
658 end
659 ActionController::Routing.use_controllers! nil
660 Object.send(:remove_const, :RAILS_ROOT) rescue nil
661 end
662
663 def test_possible_controllers_are_reset_on_each_load
664 true_possible_controllers = ActionController::Routing.possible_controllers
665 true_controller_paths = ActionController::Routing.controller_paths
666
667 ActionController::Routing.use_controllers! nil
668 root = File.dirname(__FILE__) + '/controller_fixtures'
669
670 ActionController::Routing.controller_paths = []
671 assert_equal [], ActionController::Routing.possible_controllers
672
673 ActionController::Routing.controller_paths = [
674 root, root + '/app/controllers', root + '/vendor/plugins/bad_plugin/lib'
675 ]
676 ActionController::Routing::Routes.load!
677
678 assert_equal ["admin/user", "plugin", "user"], ActionController::Routing.possible_controllers.sort
679 ensure
680 ActionController::Routing.controller_paths = true_controller_paths
681 ActionController::Routing.use_controllers! true_possible_controllers
682 Object.send(:remove_const, :RAILS_ROOT) rescue nil
683
684 ActionController::Routing::Routes.clear!
685 ActionController::Routing::Routes.load_routes!
686 end
687
688 def test_with_controllers
689 c = %w(admin/accounts admin/users account pages)
690 ActionController::Routing.with_controllers c do
691 assert_equal c, ActionController::Routing.possible_controllers
692 end
693 end
694
695 def test_normalize_unix_paths
696 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)
697 paths = ActionController::Routing.normalize_paths(load_paths)
698 assert_equal %w(vendor/rails/railties/builtin/rails_info vendor/rails/actionpack/lib app/controllers app/helpers app/models config .bar lib .), paths
699 end
700
701 def test_normalize_windows_paths
702 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)
703 paths = ActionController::Routing.normalize_paths(load_paths)
704 assert_equal %w(vendor\\rails\\railties\\builtin\\rails_info vendor\\rails\\actionpack\\lib app\\controllers app\\helpers app\\models config .bar lib .), paths
705 end
706
707 def test_routing_helper_module
708 assert_kind_of Module, ActionController::Routing::Helpers
709
710 h = ActionController::Routing::Helpers
711 c = Class.new
712 assert ! c.ancestors.include?(h)
713 ActionController::Routing::Routes.install_helpers c
714 assert c.ancestors.include?(h)
715 end
716 end
717
718 class MockController
719 attr_accessor :routes
720
721 def initialize(routes)
722 self.routes = routes
723 end
724
725 def url_for(options)
726 only_path = options.delete(:only_path)
727
728 port = options.delete(:port) || 80
729 port_string = port == 80 ? '' : ":#{port}"
730
731 protocol = options.delete(:protocol) || "http"
732 host = options.delete(:host) || "test.host"
733 anchor = "##{options.delete(:anchor)}" if options.key?(:anchor)
734
735 path = routes.generate(options)
736
737 only_path ? "#{path}#{anchor}" : "#{protocol}://#{host}#{port_string}#{path}#{anchor}"
738 end
739
740 def request
741 @request ||= ActionController::TestRequest.new
742 end
743 end
744
745 class LegacyRouteSetTests < Test::Unit::TestCase
746 attr_reader :rs
747
748 def setup
749 # These tests assume optimisation is on, so re-enable it.
750 ActionController::Base.optimise_named_routes = true
751
752 @rs = ::ActionController::Routing::RouteSet.new
753
754 ActionController::Routing.use_controllers! %w(content admin/user admin/news_feed)
755 end
756
757 def teardown
758 @rs.clear!
759 end
760
761 def test_default_setup
762 @rs.draw {|m| m.connect ':controller/:action/:id' }
763 assert_equal({:controller => "content", :action => 'index'}, rs.recognize_path("/content"))
764 assert_equal({:controller => "content", :action => 'list'}, rs.recognize_path("/content/list"))
765 assert_equal({:controller => "content", :action => 'show', :id => '10'}, rs.recognize_path("/content/show/10"))
766
767 assert_equal({:controller => "admin/user", :action => 'show', :id => '10'}, rs.recognize_path("/admin/user/show/10"))
768
769 assert_equal '/admin/user/show/10', rs.generate(:controller => 'admin/user', :action => 'show', :id => 10)
770
771 assert_equal '/admin/user/show', rs.generate({:action => 'show'}, {:controller => 'admin/user', :action => 'list', :id => '10'})
772 assert_equal '/admin/user/list/10', rs.generate({}, {:controller => 'admin/user', :action => 'list', :id => '10'})
773
774 assert_equal '/admin/stuff', rs.generate({:controller => 'stuff'}, {:controller => 'admin/user', :action => 'list', :id => '10'})
775 assert_equal '/stuff', rs.generate({:controller => '/stuff'}, {:controller => 'admin/user', :action => 'list', :id => '10'})
776 end
777
778 def test_ignores_leading_slash
779 @rs.clear!
780 @rs.draw {|m| m.connect '/:controller/:action/:id'}
781 test_default_setup
782 end
783
784 def test_time_recognition
785 # We create many routes to make situation more realistic
786 @rs = ::ActionController::Routing::RouteSet.new
787 @rs.draw { |map|
788 map.frontpage '', :controller => 'search', :action => 'new'
789 map.resources :videos do |video|
790 video.resources :comments
791 video.resource :file, :controller => 'video_file'
792 video.resource :share, :controller => 'video_shares'
793 video.resource :abuse, :controller => 'video_abuses'
794 end
795 map.resources :abuses, :controller => 'video_abuses'
796 map.resources :video_uploads
797 map.resources :video_visits
798
799 map.resources :users do |user|
800 user.resource :settings
801 user.resources :videos
802 end
803 map.resources :channels do |channel|
804 channel.resources :videos, :controller => 'channel_videos'
805 end
806 map.resource :session
807 map.resource :lost_password
808 map.search 'search', :controller => 'search'
809 map.resources :pages
810 map.connect ':controller/:action/:id'
811 }
812 n = 1000
813 if RunTimeTests
814 GC.start
815 rectime = Benchmark.realtime do
816 n.times do
817 rs.recognize_path("/videos/1234567", {:method => :get})
818 rs.recognize_path("/videos/1234567/abuse", {:method => :get})
819 rs.recognize_path("/users/1234567/settings", {:method => :get})
820 rs.recognize_path("/channels/1234567", {:method => :get})
821 rs.recognize_path("/session/new", {:method => :get})
822 rs.recognize_path("/admin/user/show/10", {:method => :get})
823 end
824 end
825 puts "\n\nRecognition (#{rs.routes.size} routes):"
826 per_url = rectime / (n * 6)
827 puts "#{per_url * 1000} ms/url"
828 puts "#{1 / per_url} url/s\n\n"
829 end
830 end
831
832 def test_time_generation
833 n = 5000
834 if RunTimeTests
835 GC.start
836 pairs = [
837 [{:controller => 'content', :action => 'index'}, {:controller => 'content', :action => 'show'}],
838 [{:controller => 'content'}, {:controller => 'content', :action => 'index'}],
839 [{:controller => 'content', :action => 'list'}, {:controller => 'content', :action => 'index'}],
840 [{:controller => 'content', :action => 'show', :id => '10'}, {:controller => 'content', :action => 'list'}],
841 [{:controller => 'admin/user', :action => 'index'}, {:controller => 'admin/user', :action => 'show'}],
842 [{:controller => 'admin/user'}, {:controller => 'admin/user', :action => 'index'}],
843 [{:controller => 'admin/user', :action => 'list'}, {:controller => 'admin/user', :action => 'index'}],
844 [{:controller => 'admin/user', :action => 'show', :id => '10'}, {:controller => 'admin/user', :action => 'list'}],
845 ]
846 p = nil
847 gentime = Benchmark.realtime do
848 n.times do
849 pairs.each {|(a, b)| rs.generate(a, b)}
850 end
851 end
852
853 puts "\n\nGeneration (RouteSet): (#{(n * 8)} urls)"
854 per_url = gentime / (n * 8)
855 puts "#{per_url * 1000} ms/url"
856 puts "#{1 / per_url} url/s\n\n"
857 end
858 end
859
860 def test_route_with_colon_first
861 rs.draw do |map|
862 map.connect '/:controller/:action/:id', :action => 'index', :id => nil
863 map.connect ':url', :controller => 'tiny_url', :action => 'translate'
864 end
865 end
866
867 def test_route_with_regexp_for_controller
868 rs.draw do |map|
869 map.connect ':controller/:admintoken/:action/:id', :controller => /admin\/.+/
870 map.connect ':controller/:action/:id'
871 end
872 assert_equal({:controller => "admin/user", :admintoken => "foo", :action => "index"},
873 rs.recognize_path("/admin/user/foo"))
874 assert_equal({:controller => "content", :action => "foo"}, rs.recognize_path("/content/foo"))
875 assert_equal '/admin/user/foo', rs.generate(:controller => "admin/user", :admintoken => "foo", :action => "index")
876 assert_equal '/content/foo', rs.generate(:controller => "content", :action => "foo")
877 end
878
879 def test_route_with_regexp_and_captures_for_controller
880 rs.draw do |map|
881 map.connect ':controller/:action/:id', :controller => /admin\/(accounts|users)/
882 end
883 assert_equal({:controller => "admin/accounts", :action => "index"}, rs.recognize_path("/admin/accounts"))
884 assert_equal({:controller => "admin/users", :action => "index"}, rs.recognize_path("/admin/users"))
885 assert_raise(ActionController::RoutingError) { rs.recognize_path("/admin/products") }
886 end
887
888 def test_route_with_regexp_and_dot
889 rs.draw do |map|
890 map.connect ':controller/:action/:file',
891 :controller => /admin|user/,
892 :action => /upload|download/,
893 :defaults => {:file => nil},
894 :requirements => {:file => %r{[^/]+(\.[^/]+)?}}
895 end
896 # Without a file extension
897 assert_equal '/user/download/file',
898 rs.generate(:controller => "user", :action => "download", :file => "file")
899 assert_equal(
900 {:controller => "user", :action => "download", :file => "file"},
901 rs.recognize_path("/user/download/file"))
902
903 # Now, let's try a file with an extension, really a dot (.)
904 assert_equal '/user/download/file.jpg',
905 rs.generate(
906 :controller => "user", :action => "download", :file => "file.jpg")
907 assert_equal(
908 {:controller => "user", :action => "download", :file => "file.jpg"},
909 rs.recognize_path("/user/download/file.jpg"))
910 end
911
912 def test_basic_named_route
913 rs.add_named_route :home, '', :controller => 'content', :action => 'list'
914 x = setup_for_named_route
915 assert_equal("http://test.host/",
916 x.send(:home_url))
917 end
918
919 def test_basic_named_route_with_relative_url_root
920 rs.add_named_route :home, '', :controller => 'content', :action => 'list'
921 x = setup_for_named_route
922 ActionController::Base.relative_url_root = "/foo"
923 assert_equal("http://test.host/foo/",
924 x.send(:home_url))
925 assert_equal "/foo/", x.send(:home_path)
926 ActionController::Base.relative_url_root = nil
927 end
928
929 def test_named_route_with_option
930 rs.add_named_route :page, 'page/:title', :controller => 'content', :action => 'show_page'
931 x = setup_for_named_route
932 assert_equal("http://test.host/page/new%20stuff",
933 x.send(:page_url, :title => 'new stuff'))
934 end
935
936 def test_named_route_with_default
937 rs.add_named_route :page, 'page/:title', :controller => 'content', :action => 'show_page', :title => 'AboutPage'
938 x = setup_for_named_route
939 assert_equal("http://test.host/page/AboutRails",
940 x.send(:page_url, :title => "AboutRails"))
941
942 end
943
944 def test_named_route_with_name_prefix
945 rs.add_named_route :page, 'page', :controller => 'content', :action => 'show_page', :name_prefix => 'my_'
946 x = setup_for_named_route
947 assert_equal("http://test.host/page",
948 x.send(:my_page_url))
949 end
950
951 def test_named_route_with_path_prefix
952 rs.add_named_route :page, 'page', :controller => 'content', :action => 'show_page', :path_prefix => 'my'
953 x = setup_for_named_route
954 assert_equal("http://test.host/my/page",
955 x.send(:page_url))
956 end
957
958 def test_named_route_with_blank_path_prefix
959 rs.add_named_route :page, 'page', :controller => 'content', :action => 'show_page', :path_prefix => ''
960 x = setup_for_named_route
961 assert_equal("http://test.host/page",
962 x.send(:page_url))
963 end
964
965 def test_named_route_with_nested_controller
966 rs.add_named_route :users, 'admin/user', :controller => 'admin/user', :action => 'index'
967 x = setup_for_named_route
968 assert_equal("http://test.host/admin/user",
969 x.send(:users_url))
970 end
971
972 def test_optimised_named_route_call_never_uses_url_for
973 rs.add_named_route :users, 'admin/user', :controller => '/admin/user', :action => 'index'
974 rs.add_named_route :user, 'admin/user/:id', :controller=>'/admin/user', :action=>'show'
975 x = setup_for_named_route
976 x.expects(:url_for).never
977 x.send(:users_url)
978 x.send(:users_path)
979 x.send(:user_url, 2, :foo=>"bar")
980 x.send(:user_path, 3, :bar=>"foo")
981 end
982
983 def test_optimised_named_route_with_host
984 rs.add_named_route :pages, 'pages', :controller => 'content', :action => 'show_page', :host => 'foo.com'
985 x = setup_for_named_route
986 x.expects(:url_for).with(:host => 'foo.com', :only_path => false, :controller => 'content', :action => 'show_page', :use_route => :pages).once
987 x.send(:pages_url)
988 end
989
990 def setup_for_named_route
991 klass = Class.new(MockController)
992 rs.install_helpers(klass)
993 klass.new(rs)
994 end
995
996 def test_named_route_without_hash
997 rs.draw do |map|
998 map.normal ':controller/:action/:id'
999 end
1000 end
1001
1002 def test_named_route_root
1003 rs.draw do |map|
1004 map.root :controller => "hello"
1005 end
1006 x = setup_for_named_route
1007 assert_equal("http://test.host/", x.send(:root_url))
1008 assert_equal("/", x.send(:root_path))
1009 end
1010
1011 def test_named_route_with_regexps
1012 rs.draw do |map|
1013 map.article 'page/:year/:month/:day/:title', :controller => 'page', :action => 'show',
1014 :year => /\d+/, :month => /\d+/, :day => /\d+/
1015 map.connect ':controller/:action/:id'
1016 end
1017 x = setup_for_named_route
1018 # assert_equal(
1019 # {:controller => 'page', :action => 'show', :title => 'hi', :use_route => :article, :only_path => false},
1020 # x.send(:article_url, :title => 'hi')
1021 # )
1022 assert_equal(
1023 "http://test.host/page/2005/6/10/hi",
1024 x.send(:article_url, :title => 'hi', :day => 10, :year => 2005, :month => 6)
1025 )
1026 end
1027
1028 def test_changing_controller
1029 @rs.draw {|m| m.connect ':controller/:action/:id' }
1030
1031 assert_equal '/admin/stuff/show/10', rs.generate(
1032 {:controller => 'stuff', :action => 'show', :id => 10},
1033 {:controller => 'admin/user', :action => 'index'}
1034 )
1035 end
1036
1037 def test_paths_escaped
1038 rs.draw do |map|
1039 map.path 'file/*path', :controller => 'content', :action => 'show_file'
1040 map.connect ':controller/:action/:id'
1041 end
1042
1043 # No + to space in URI escaping, only for query params.
1044 results = rs.recognize_path "/file/hello+world/how+are+you%3F"
1045 assert results, "Recognition should have succeeded"
1046 assert_equal ['hello+world', 'how+are+you?'], results[:path]
1047
1048 # Use %20 for space instead.
1049 results = rs.recognize_path "/file/hello%20world/how%20are%20you%3F"
1050 assert results, "Recognition should have succeeded"
1051 assert_equal ['hello world', 'how are you?'], results[:path]
1052
1053 results = rs.recognize_path "/file"
1054 assert results, "Recognition should have succeeded"
1055 assert_equal [], results[:path]
1056 end
1057
1058 def test_paths_slashes_unescaped_with_ordered_parameters
1059 rs.add_named_route :path, '/file/*path', :controller => 'content'
1060
1061 # No / to %2F in URI, only for query params.
1062 x = setup_for_named_route
1063 assert_equal("/file/hello/world", x.send(:path_path, 'hello/world'))
1064 end
1065
1066 def test_non_controllers_cannot_be_matched
1067 rs.draw do |map|
1068 map.connect ':controller/:action/:id'
1069 end
1070 assert_raise(ActionController::RoutingError) { rs.recognize_path("/not_a/show/10") }
1071 end
1072
1073 def test_paths_do_not_accept_defaults
1074 assert_raise(ActionController::RoutingError) do
1075 rs.draw do |map|
1076 map.path 'file/*path', :controller => 'content', :action => 'show_file', :path => %w(fake default)
1077 map.connect ':controller/:action/:id'
1078 end
1079 end
1080
1081 rs.draw do |map|
1082 map.path 'file/*path', :controller => 'content', :action => 'show_file', :path => []
1083 map.connect ':controller/:action/:id'
1084 end
1085 end
1086
1087 def test_should_list_options_diff_when_routing_requirements_dont_match
1088 rs.draw do |map|
1089 map.post 'post/:id', :controller=> 'post', :action=> 'show', :requirements => {:id => /\d+/}
1090 end
1091 exception = assert_raise(ActionController::RoutingError) { rs.generate(:controller => 'post', :action => 'show', :bad_param => "foo", :use_route => "post") }
1092 assert_match /^post_url failed to generate/, exception.message
1093 from_match = exception.message.match(/from \{[^\}]+\}/).to_s
1094 assert_match /:bad_param=>"foo"/, from_match
1095 assert_match /:action=>"show"/, from_match
1096 assert_match /:controller=>"post"/, from_match
1097
1098 expected_match = exception.message.match(/expected: \{[^\}]+\}/).to_s
1099 assert_no_match /:bad_param=>"foo"/, expected_match
1100 assert_match /:action=>"show"/, expected_match
1101 assert_match /:controller=>"post"/, expected_match
1102
1103 diff_match = exception.message.match(/diff: \{[^\}]+\}/).to_s
1104 assert_match /:bad_param=>"foo"/, diff_match
1105 assert_no_match /:action=>"show"/, diff_match
1106 assert_no_match /:controller=>"post"/, diff_match
1107 end
1108
1109 # this specifies the case where your formerly would get a very confusing error message with an empty diff
1110 def test_should_have_better_error_message_when_options_diff_is_empty
1111 rs.draw do |map|
1112 map.content '/content/:query', :controller => 'content', :action => 'show'
1113 end
1114
1115 exception = assert_raise(ActionController::RoutingError) { rs.generate(:controller => 'content', :action => 'show', :use_route => "content") }
1116 assert_match %r[:action=>"show"], exception.message
1117 assert_match %r[:controller=>"content"], exception.message
1118 assert_match %r[you may have ambiguous routes, or you may need to supply additional parameters for this route], exception.message
1119 assert_match %r[content_url has the following required parameters: \["content", :query\] - are they all satisfied?], exception.message
1120 end
1121
1122 def test_dynamic_path_allowed
1123 rs.draw do |map|
1124 map.connect '*path', :controller => 'content', :action => 'show_file'
1125 end
1126
1127 assert_equal '/pages/boo', rs.generate(:controller => 'content', :action => 'show_file', :path => %w(pages boo))
1128 end
1129
1130 def test_dynamic_recall_paths_allowed
1131 rs.draw do |map|
1132 map.connect '*path', :controller => 'content', :action => 'show_file'
1133 end
1134
1135 recall_path = ActionController::Routing::PathSegment::Result.new(%w(pages boo))
1136 assert_equal '/pages/boo', rs.generate({}, :controller => 'content', :action => 'show_file', :path => recall_path)
1137 end
1138
1139 def test_backwards
1140 rs.draw do |map|
1141 map.connect 'page/:id/:action', :controller => 'pages', :action => 'show'
1142 map.connect ':controller/:action/:id'
1143 end
1144
1145 assert_equal '/page/20', rs.generate({:id => 20}, {:controller => 'pages', :action => 'show'})
1146 assert_equal '/page/20', rs.generate(:controller => 'pages', :id => 20, :action => 'show')
1147 assert_equal '/pages/boo', rs.generate(:controller => 'pages', :action => 'boo')
1148 end
1149
1150 def test_route_with_fixnum_default
1151 rs.draw do |map|
1152 map.connect 'page/:id', :controller => 'content', :action => 'show_page', :id => 1
1153 map.connect ':controller/:action/:id'
1154 end
1155
1156 assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page')
1157 assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page', :id => 1)
1158 assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page', :id => '1')
1159 assert_equal '/page/10', rs.generate(:controller => 'content', :action => 'show_page', :id => 10)
1160
1161 assert_equal({:controller => "content", :action => 'show_page', :id => '1'}, rs.recognize_path("/page"))
1162 assert_equal({:controller => "content", :action => 'show_page', :id => '1'}, rs.recognize_path("/page/1"))
1163 assert_equal({:controller => "content", :action => 'show_page', :id => '10'}, rs.recognize_path("/page/10"))
1164 end
1165
1166 # For newer revision
1167 def test_route_with_text_default
1168 rs.draw do |map|
1169 map.connect 'page/:id', :controller => 'content', :action => 'show_page', :id => 1
1170 map.connect ':controller/:action/:id'
1171 end
1172
1173 assert_equal '/page/foo', rs.generate(:controller => 'content', :action => 'show_page', :id => 'foo')
1174 assert_equal({:controller => "content", :action => 'show_page', :id => 'foo'}, rs.recognize_path("/page/foo"))
1175
1176 token = "\321\202\320\265\320\272\321\201\321\202" # 'text' in russian
1177 token.force_encoding("UTF-8") if token.respond_to?(:force_encoding)
1178 escaped_token = CGI::escape(token)
1179
1180 assert_equal '/page/' + escaped_token, rs.generate(:controller => 'content', :action => 'show_page', :id => token)
1181 assert_equal({:controller => "content", :action => 'show_page', :id => token}, rs.recognize_path("/page/#{escaped_token}"))
1182 end
1183
1184 def test_action_expiry
1185 @rs.draw {|m| m.connect ':controller/:action/:id' }
1186 assert_equal '/content', rs.generate({:controller => 'content'}, {:controller => 'content', :action => 'show'})
1187 end
1188
1189 def test_recognition_with_uppercase_controller_name
1190 @rs.draw {|m| m.connect ':controller/:action/:id' }
1191 assert_equal({:controller => "content", :action => 'index'}, rs.recognize_path("/Content"))
1192 assert_equal({:controller => "content", :action => 'list'}, rs.recognize_path("/ConTent/list"))
1193 assert_equal({:controller => "content", :action => 'show', :id => '10'}, rs.recognize_path("/CONTENT/show/10"))
1194
1195 # these used to work, before the routes rewrite, but support for this was pulled in the new version...
1196 #assert_equal({'controller' => "admin/news_feed", 'action' => 'index'}, rs.recognize_path("Admin/NewsFeed"))
1197 #assert_equal({'controller' => "admin/news_feed", 'action' => 'index'}, rs.recognize_path("Admin/News_Feed"))
1198 end
1199
1200 def test_requirement_should_prevent_optional_id
1201 rs.draw do |map|
1202 map.post 'post/:id', :controller=> 'post', :action=> 'show', :requirements => {:id => /\d+/}
1203 end
1204
1205 assert_equal '/post/10', rs.generate(:controller => 'post', :action => 'show', :id => 10)
1206
1207 assert_raise ActionController::RoutingError do
1208 rs.generate(:controller => 'post', :action => 'show')
1209 end
1210 end
1211
1212 def test_both_requirement_and_optional
1213 rs.draw do |map|
1214 map.blog('test/:year', :controller => 'post', :action => 'show',
1215 :defaults => { :year => nil },
1216 :requirements => { :year => /\d{4}/ }
1217 )
1218 map.connect ':controller/:action/:id'
1219 end
1220
1221 assert_equal '/test', rs.generate(:controller => 'post', :action => 'show')
1222 assert_equal '/test', rs.generate(:controller => 'post', :action => 'show', :year => nil)
1223
1224 x = setup_for_named_route
1225 assert_equal("http://test.host/test",
1226 x.send(:blog_url))
1227 end
1228
1229 def test_set_to_nil_forgets
1230 rs.draw do |map|
1231 map.connect 'pages/:year/:month/:day', :controller => 'content', :action => 'list_pages', :month => nil, :day => nil
1232 map.connect ':controller/:action/:id'
1233 end
1234
1235 assert_equal '/pages/2005',
1236 rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005)
1237 assert_equal '/pages/2005/6',
1238 rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005, :month => 6)
1239 assert_equal '/pages/2005/6/12',
1240 rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005, :month => 6, :day => 12)
1241
1242 assert_equal '/pages/2005/6/4',
1243 rs.generate({:day => 4}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'})
1244
1245 assert_equal '/pages/2005/6',
1246 rs.generate({:day => nil}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'})
1247
1248 assert_equal '/pages/2005',
1249 rs.generate({:day => nil, :month => nil}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'})
1250 end
1251
1252 def test_url_with_no_action_specified
1253 rs.draw do |map|
1254 map.connect '', :controller => 'content'
1255 map.connect ':controller/:action/:id'
1256 end
1257
1258 assert_equal '/', rs.generate(:controller => 'content', :action => 'index')
1259 assert_equal '/', rs.generate(:controller => 'content')
1260 end
1261
1262 def test_named_url_with_no_action_specified
1263 rs.draw do |map|
1264 map.home '', :controller => 'content'
1265 map.connect ':controller/:action/:id'
1266 end
1267
1268 assert_equal '/', rs.generate(:controller => 'content', :action => 'index')
1269 assert_equal '/', rs.generate(:controller => 'content')
1270
1271 x = setup_for_named_route
1272 assert_equal("http://test.host/",
1273 x.send(:home_url))
1274 end
1275
1276 def test_url_generated_when_forgetting_action
1277 [{:controller => 'content', :action => 'index'}, {:controller => 'content'}].each do |hash|
1278 rs.draw do |map|
1279 map.home '', hash
1280 map.connect ':controller/:action/:id'
1281 end
1282 assert_equal '/', rs.generate({:action => nil}, {:controller => 'content', :action => 'hello'})
1283 assert_equal '/', rs.generate({:controller => 'content'})
1284 assert_equal '/content/hi', rs.generate({:controller => 'content', :action => 'hi'})
1285 end
1286 end
1287
1288 def test_named_route_method
1289 rs.draw do |map|
1290 map.categories 'categories', :controller => 'content', :action => 'categories'
1291 map.connect ':controller/:action/:id'
1292 end
1293
1294 assert_equal '/categories', rs.generate(:controller => 'content', :action => 'categories')
1295 assert_equal '/content/hi', rs.generate({:controller => 'content', :action => 'hi'})
1296 end
1297
1298 def test_named_routes_array
1299 test_named_route_method
1300 assert_equal [:categories], rs.named_routes.names
1301 end
1302
1303 def test_nil_defaults
1304 rs.draw do |map|
1305 map.connect 'journal',
1306 :controller => 'content',
1307 :action => 'list_journal',
1308 :date => nil, :user_id => nil
1309 map.connect ':controller/:action/:id'
1310 end
1311
1312 assert_equal '/journal', rs.generate(:controller => 'content', :action => 'list_journal', :date => nil, :user_id => nil)
1313 end
1314
1315 def setup_request_method_routes_for(method)
1316 @request = ActionController::TestRequest.new
1317 @request.env["REQUEST_METHOD"] = method
1318 @request.request_uri = "/match"
1319
1320 rs.draw do |r|
1321 r.connect '/match', :controller => 'books', :action => 'get', :conditions => { :method => :get }
1322 r.connect '/match', :controller => 'books', :action => 'post', :conditions => { :method => :post }
1323 r.connect '/match', :controller => 'books', :action => 'put', :conditions => { :method => :put }
1324 r.connect '/match', :controller => 'books', :action => 'delete', :conditions => { :method => :delete }
1325 end
1326 end
1327
1328 %w(GET POST PUT DELETE).each do |request_method|
1329 define_method("test_request_method_recognized_with_#{request_method}") do
1330 begin
1331 Object.const_set(:BooksController, Class.new(ActionController::Base))
1332
1333 setup_request_method_routes_for(request_method)
1334
1335 assert_nothing_raised { rs.recognize(@request) }
1336 assert_equal request_method.downcase, @request.path_parameters[:action]
1337 ensure
1338 Object.send(:remove_const, :BooksController) rescue nil
1339 end
1340 end
1341 end
1342
1343 def test_recognize_array_of_methods
1344 Object.const_set(:BooksController, Class.new(ActionController::Base))
1345 rs.draw do |r|
1346 r.connect '/match', :controller => 'books', :action => 'get_or_post', :conditions => { :method => [:get, :post] }
1347 r.connect '/match', :controller => 'books', :action => 'not_get_or_post'
1348 end
1349
1350 @request = ActionController::TestRequest.new
1351 @request.env["REQUEST_METHOD"] = 'POST'
1352 @request.request_uri = "/match"
1353 assert_nothing_raised { rs.recognize(@request) }
1354 assert_equal 'get_or_post', @request.path_parameters[:action]
1355
1356 # have to recreate or else the RouteSet uses a cached version:
1357 @request = ActionController::TestRequest.new
1358 @request.env["REQUEST_METHOD"] = 'PUT'
1359 @request.request_uri = "/match"
1360 assert_nothing_raised { rs.recognize(@request) }
1361 assert_equal 'not_get_or_post', @request.path_parameters[:action]
1362 ensure
1363 Object.send(:remove_const, :BooksController) rescue nil
1364 end
1365
1366 def test_subpath_recognized
1367 Object.const_set(:SubpathBooksController, Class.new(ActionController::Base))
1368
1369 rs.draw do |r|
1370 r.connect '/books/:id/edit', :controller => 'subpath_books', :action => 'edit'
1371 r.connect '/items/:id/:action', :controller => 'subpath_books'
1372 r.connect '/posts/new/:action', :controller => 'subpath_books'
1373 r.connect '/posts/:id', :controller => 'subpath_books', :action => "show"
1374 end
1375
1376 hash = rs.recognize_path "/books/17/edit"
1377 assert_not_nil hash
1378 assert_equal %w(subpath_books 17 edit), [hash[:controller], hash[:id], hash[:action]]
1379
1380 hash = rs.recognize_path "/items/3/complete"
1381 assert_not_nil hash
1382 assert_equal %w(subpath_books 3 complete), [hash[:controller], hash[:id], hash[:action]]
1383
1384 hash = rs.recognize_path "/posts/new/preview"
1385 assert_not_nil hash
1386 assert_equal %w(subpath_books preview), [hash[:controller], hash[:action]]
1387
1388 hash = rs.recognize_path "/posts/7"
1389 assert_not_nil hash
1390 assert_equal %w(subpath_books show 7), [hash[:controller], hash[:action], hash[:id]]
1391 ensure
1392 Object.send(:remove_const, :SubpathBooksController) rescue nil
1393 end
1394
1395 def test_subpath_generated
1396 Object.const_set(:SubpathBooksController, Class.new(ActionController::Base))
1397
1398 rs.draw do |r|
1399 r.connect '/books/:id/edit', :controller => 'subpath_books', :action => 'edit'
1400 r.connect '/items/:id/:action', :controller => 'subpath_books'
1401 r.connect '/posts/new/:action', :controller => 'subpath_books'
1402 end
1403
1404 assert_equal "/books/7/edit", rs.generate(:controller => "subpath_books", :id => 7, :action => "edit")
1405 assert_equal "/items/15/complete", rs.generate(:controller => "subpath_books", :id => 15, :action => "complete")
1406 assert_equal "/posts/new/preview", rs.generate(:controller => "subpath_books", :action => "preview")
1407 ensure
1408 Object.send(:remove_const, :SubpathBooksController) rescue nil
1409 end
1410
1411 def test_failed_requirements_raises_exception_with_violated_requirements
1412 rs.draw do |r|
1413 r.foo_with_requirement 'foos/:id', :controller=>'foos', :requirements=>{:id=>/\d+/}
1414 end
1415
1416 x = setup_for_named_route
1417 assert_raise(ActionController::RoutingError) do
1418 x.send(:foo_with_requirement_url, "I am Against the requirements")
1419 end
1420 end
1421
1422 def test_routes_changed_correctly_after_clear
1423 ActionController::Base.optimise_named_routes = true
1424 rs = ::ActionController::Routing::RouteSet.new
1425 rs.draw do |r|
1426 r.connect 'ca', :controller => 'ca', :action => "aa"
1427 r.connect 'cb', :controller => 'cb', :action => "ab"
1428 r.connect 'cc', :controller => 'cc', :action => "ac"
1429 r.connect ':controller/:action/:id'
1430 r.connect ':controller/:action/:id.:format'
1431 end
1432
1433 hash = rs.recognize_path "/cc"
1434
1435 assert_not_nil hash
1436 assert_equal %w(cc ac), [hash[:controller], hash[:action]]
1437
1438 rs.draw do |r|
1439 r.connect 'cb', :controller => 'cb', :action => "ab"
1440 r.connect 'cc', :controller => 'cc', :action => "ac"
1441 r.connect ':controller/:action/:id'
1442 r.connect ':controller/:action/:id.:format'
1443 end
1444
1445 hash = rs.recognize_path "/cc"
1446
1447 assert_not_nil hash
1448 assert_equal %w(cc ac), [hash[:controller], hash[:action]]
1449
1450 end
1451 end
1452
1453 class RouteTest < Test::Unit::TestCase
1454 def setup
1455 @route = ROUTING::Route.new
1456 end
1457
1458 def slash_segment(is_optional = false)
1459 ROUTING::DividerSegment.new('/', :optional => is_optional)
1460 end
1461
1462 def default_route
1463 unless defined?(@default_route)
1464 segments = []
1465 segments << ROUTING::StaticSegment.new('/', :raw => true)
1466 segments << ROUTING::DynamicSegment.new(:controller)
1467 segments << slash_segment(:optional)
1468 segments << ROUTING::DynamicSegment.new(:action, :default => 'index', :optional => true)
1469 segments << slash_segment(:optional)
1470 segments << ROUTING::DynamicSegment.new(:id, :optional => true)
1471 segments << slash_segment(:optional)
1472 @default_route = ROUTING::Route.new(segments).freeze
1473 end
1474 @default_route
1475 end
1476
1477 def test_default_route_recognition
1478 expected = {:controller => 'accounts', :action => 'show', :id => '10'}
1479 assert_equal expected, default_route.recognize('/accounts/show/10')
1480 assert_equal expected, default_route.recognize('/accounts/show/10/')
1481
1482 expected[:id] = 'jamis'
1483 assert_equal expected, default_route.recognize('/accounts/show/jamis/')
1484
1485 expected.delete :id
1486 assert_equal expected, default_route.recognize('/accounts/show')
1487 assert_equal expected, default_route.recognize('/accounts/show/')
1488
1489 expected[:action] = 'index'
1490 assert_equal expected, default_route.recognize('/accounts/')
1491 assert_equal expected, default_route.recognize('/accounts')
1492
1493 assert_equal nil, default_route.recognize('/')
1494 assert_equal nil, default_route.recognize('/accounts/how/goood/it/is/to/be/free')
1495 end
1496
1497 def test_default_route_should_omit_default_action
1498 o = {:controller => 'accounts', :action => 'index'}
1499 assert_equal '/accounts', default_route.generate(o, o, {})
1500 end
1501
1502 def test_default_route_should_include_default_action_when_id_present
1503 o = {:controller => 'accounts', :action => 'index', :id => '20'}
1504 assert_equal '/accounts/index/20', default_route.generate(o, o, {})
1505 end
1506
1507 def test_default_route_should_work_with_action_but_no_id
1508 o = {:controller => 'accounts', :action => 'list_all'}
1509 assert_equal '/accounts/list_all', default_route.generate(o, o, {})
1510 end
1511
1512 def test_default_route_should_uri_escape_pluses
1513 expected = { :controller => 'accounts', :action => 'show', :id => 'hello world' }
1514 assert_equal expected, default_route.recognize('/accounts/show/hello world')
1515 assert_equal expected, default_route.recognize('/accounts/show/hello%20world')
1516 assert_equal '/accounts/show/hello%20world', default_route.generate(expected, expected, {})
1517
1518 expected[:id] = 'hello+world'
1519 assert_equal expected, default_route.recognize('/accounts/show/hello+world')
1520 assert_equal expected, default_route.recognize('/accounts/show/hello%2Bworld')
1521 assert_equal '/accounts/show/hello+world', default_route.generate(expected, expected, {})
1522 end
1523
1524 def test_matches_controller_and_action
1525 # requirement_for should only be called for the action and controller _once_
1526 @route.expects(:requirement_for).with(:controller).times(1).returns('pages')
1527 @route.expects(:requirement_for).with(:action).times(1).returns('show')
1528
1529 @route.requirements = {:controller => 'pages', :action => 'show'}
1530 assert @route.matches_controller_and_action?('pages', 'show')
1531 assert !@route.matches_controller_and_action?('not_pages', 'show')
1532 assert !@route.matches_controller_and_action?('pages', 'not_show')
1533 end
1534
1535 def test_parameter_shell
1536 page_url = ROUTING::Route.new
1537 page_url.requirements = {:controller => 'pages', :action => 'show', :id => /\d+/}
1538 assert_equal({:controller => 'pages', :action => 'show'}, page_url.parameter_shell)
1539 end
1540
1541 def test_defaults
1542 route = ROUTING::RouteBuilder.new.build '/users/:id.:format', :controller => "users", :action => "show", :format => "html"
1543 assert_equal(
1544 { :controller => "users", :action => "show", :format => "html" },
1545 route.defaults)
1546 end
1547
1548 def test_builder_complains_without_controller
1549 assert_raise(ArgumentError) do
1550 ROUTING::RouteBuilder.new.build '/contact', :contoller => "contact", :action => "index"
1551 end
1552 end
1553
1554 def test_significant_keys_for_default_route
1555 keys = default_route.significant_keys.sort_by {|k| k.to_s }
1556 assert_equal [:action, :controller, :id], keys
1557 end
1558
1559 def test_significant_keys
1560 segments = []
1561 segments << ROUTING::StaticSegment.new('/', :raw => true)
1562 segments << ROUTING::StaticSegment.new('user')
1563 segments << ROUTING::StaticSegment.new('/', :raw => true, :optional => true)
1564 segments << ROUTING::DynamicSegment.new(:user)
1565 segments << ROUTING::StaticSegment.new('/', :raw => true, :optional => true)
1566
1567 requirements = {:controller => 'users', :action => 'show'}
1568
1569 user_url = ROUTING::Route.new(segments, requirements)
1570 keys = user_url.significant_keys.sort_by { |k| k.to_s }
1571 assert_equal [:action, :controller, :user], keys
1572 end
1573
1574 def test_build_empty_query_string
1575 assert_equal '', @route.build_query_string({})
1576 end
1577
1578 def test_build_query_string_with_nil_value
1579 assert_equal '', @route.build_query_string({:x => nil})
1580 end
1581
1582 def test_simple_build_query_string
1583 assert_equal '?x=1&y=2', order_query_string(@route.build_query_string(:x => '1', :y => '2'))
1584 end
1585
1586 def test_convert_ints_build_query_string
1587 assert_equal '?x=1&y=2', order_query_string(@route.build_query_string(:x => 1, :y => 2))
1588 end
1589
1590 def test_escape_spaces_build_query_string
1591 assert_equal '?x=hello+world&y=goodbye+world', order_query_string(@route.build_query_string(:x => 'hello world', :y => 'goodbye world'))
1592 end
1593
1594 def test_expand_array_build_query_string
1595 assert_equal '?x%5B%5D=1&x%5B%5D=2', order_query_string(@route.build_query_string(:x => [1, 2]))
1596 end
1597
1598 def test_escape_spaces_build_query_string_selected_keys
1599 assert_equal '?x=hello+world', order_query_string(@route.build_query_string({:x => 'hello world', :y => 'goodbye world'}, [:x]))
1600 end
1601
1602 private
1603 def order_query_string(qs)
1604 '?' + qs[1..-1].split('&').sort.join('&')
1605 end
1606 end
1607
1608 class RouteSetTest < Test::Unit::TestCase
1609 def set
1610 @set ||= ROUTING::RouteSet.new
1611 end
1612
1613 def request
1614 @request ||= ActionController::TestRequest.new
1615 end
1616
1617 def test_generate_extras
1618 set.draw { |m| m.connect ':controller/:action/:id' }
1619 path, extras = set.generate_extras(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
1620 assert_equal "/foo/bar/15", path
1621 assert_equal %w(that this), extras.map(&:to_s).sort
1622 end
1623
1624 def test_extra_keys
1625 set.draw { |m| m.connect ':controller/:action/:id' }
1626 extras = set.extra_keys(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
1627 assert_equal %w(that this), extras.map(&:to_s).sort
1628 end
1629
1630 def test_generate_extras_not_first
1631 set.draw do |map|
1632 map.connect ':controller/:action/:id.:format'
1633 map.connect ':controller/:action/:id'
1634 end
1635 path, extras = set.generate_extras(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
1636 assert_equal "/foo/bar/15", path
1637 assert_equal %w(that this), extras.map(&:to_s).sort
1638 end
1639
1640 def test_generate_not_first
1641 set.draw do |map|
1642 map.connect ':controller/:action/:id.:format'
1643 map.connect ':controller/:action/:id'
1644 end
1645 assert_equal "/foo/bar/15?this=hello", set.generate(:controller => "foo", :action => "bar", :id => 15, :this => "hello")
1646 end
1647
1648 def test_extra_keys_not_first
1649 set.draw do |map|
1650 map.connect ':controller/:action/:id.:format'
1651 map.connect ':controller/:action/:id'
1652 end
1653 extras = set.extra_keys(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
1654 assert_equal %w(that this), extras.map(&:to_s).sort
1655 end
1656
1657 def test_draw
1658 assert_equal 0, set.routes.size
1659 set.draw do |map|
1660 map.connect '/hello/world', :controller => 'a', :action => 'b'
1661 end
1662 assert_equal 1, set.routes.size
1663 end
1664
1665 def test_named_draw
1666 assert_equal 0, set.routes.size
1667 set.draw do |map|
1668 map.hello '/hello/world', :controller => 'a', :action => 'b'
1669 end
1670 assert_equal 1, set.routes.size
1671 assert_equal set.routes.first, set.named_routes[:hello]
1672 end
1673
1674 def test_later_named_routes_take_precedence
1675 set.draw do |map|
1676 map.hello '/hello/world', :controller => 'a', :action => 'b'
1677 map.hello '/hello', :controller => 'a', :action => 'b'
1678 end
1679 assert_equal set.routes.last, set.named_routes[:hello]
1680 end
1681
1682 def setup_named_route_test
1683 set.draw do |map|
1684 map.show '/people/:id', :controller => 'people', :action => 'show'
1685 map.index '/people', :controller => 'people', :action => 'index'
1686 map.multi '/people/go/:foo/:bar/joe/:id', :controller => 'people', :action => 'multi'
1687 map.users '/admin/users', :controller => 'admin/users', :action => 'index'
1688 end
1689
1690 klass = Class.new(MockController)
1691 set.install_helpers(klass)
1692 klass.new(set)
1693 end
1694
1695 def test_named_route_hash_access_method
1696 controller = setup_named_route_test
1697
1698 assert_equal(
1699 { :controller => 'people', :action => 'show', :id => 5, :use_route => :show, :only_path => false },
1700 controller.send(:hash_for_show_url, :id => 5))
1701
1702 assert_equal(
1703 { :controller => 'people', :action => 'index', :use_route => :index, :only_path => false },
1704 controller.send(:hash_for_index_url))
1705
1706 assert_equal(
1707 { :controller => 'people', :action => 'show', :id => 5, :use_route => :show, :only_path => true },
1708 controller.send(:hash_for_show_path, :id => 5)
1709 )
1710 end
1711
1712 def test_named_route_url_method
1713 controller = setup_named_route_test
1714
1715 assert_equal "http://test.host/people/5", controller.send(:show_url, :id => 5)
1716 assert_equal "/people/5", controller.send(:show_path, :id => 5)
1717
1718 assert_equal "http://test.host/people", controller.send(:index_url)
1719 assert_equal "/people", controller.send(:index_path)
1720
1721 assert_equal "http://test.host/admin/users", controller.send(:users_url)
1722 assert_equal '/admin/users', controller.send(:users_path)
1723 assert_equal '/admin/users', set.generate(controller.send(:hash_for_users_url), {:controller => 'users', :action => 'index'})
1724 end
1725
1726 def test_named_route_url_method_with_anchor
1727 controller = setup_named_route_test
1728
1729 assert_equal "http://test.host/people/5#location", controller.send(:show_url, :id => 5, :anchor => 'location')
1730 assert_equal "/people/5#location", controller.send(:show_path, :id => 5, :anchor => 'location')
1731
1732 assert_equal "http://test.host/people#location", controller.send(:index_url, :anchor => 'location')
1733 assert_equal "/people#location", controller.send(:index_path, :anchor => 'location')
1734
1735 assert_equal "http://test.host/admin/users#location", controller.send(:users_url, :anchor => 'location')
1736 assert_equal '/admin/users#location', controller.send(:users_path, :anchor => 'location')
1737
1738 assert_equal "http://test.host/people/go/7/hello/joe/5#location",
1739 controller.send(:multi_url, 7, "hello", 5, :anchor => 'location')
1740
1741 assert_equal "http://test.host/people/go/7/hello/joe/5?baz=bar#location",
1742 controller.send(:multi_url, 7, "hello", 5, :baz => "bar", :anchor => 'location')
1743
1744 assert_equal "http://test.host/people?baz=bar#location",
1745 controller.send(:index_url, :baz => "bar", :anchor => 'location')
1746 end
1747
1748 def test_named_route_url_method_with_port
1749 controller = setup_named_route_test
1750 assert_equal "http://test.host:8080/people/5", controller.send(:show_url, 5, :port=>8080)
1751 end
1752
1753 def test_named_route_url_method_with_host
1754 controller = setup_named_route_test
1755 assert_equal "http://some.example.com/people/5", controller.send(:show_url, 5, :host=>"some.example.com")
1756 end
1757
1758 def test_named_route_url_method_with_protocol
1759 controller = setup_named_route_test
1760 assert_equal "https://test.host/people/5", controller.send(:show_url, 5, :protocol => "https")
1761 end
1762
1763 def test_named_route_url_method_with_ordered_parameters
1764 controller = setup_named_route_test
1765 assert_equal "http://test.host/people/go/7/hello/joe/5",
1766 controller.send(:multi_url, 7, "hello", 5)
1767 end
1768
1769 def test_named_route_url_method_with_ordered_parameters_and_hash
1770 controller = setup_named_route_test
1771 assert_equal "http://test.host/people/go/7/hello/joe/5?baz=bar",
1772 controller.send(:multi_url, 7, "hello", 5, :baz => "bar")
1773 end
1774
1775 def test_named_route_url_method_with_ordered_parameters_and_empty_hash
1776 controller = setup_named_route_test
1777 assert_equal "http://test.host/people/go/7/hello/joe/5",
1778 controller.send(:multi_url, 7, "hello", 5, {})
1779 end
1780
1781 def test_named_route_url_method_with_no_positional_arguments
1782 controller = setup_named_route_test
1783 assert_equal "http://test.host/people?baz=bar",
1784 controller.send(:index_url, :baz => "bar")
1785 end
1786
1787 def test_draw_default_route
1788 ActionController::Routing.with_controllers(['users']) do
1789 set.draw do |map|
1790 map.connect '/:controller/:action/:id'
1791 end
1792
1793 assert_equal 1, set.routes.size
1794 route = set.routes.first
1795
1796 assert route.segments.last.optional?
1797
1798 assert_equal '/users/show/10', set.generate(:controller => 'users', :action => 'show', :id => 10)
1799 assert_equal '/users/index/10', set.generate(:controller => 'users', :id => 10)
1800
1801 assert_equal({:controller => 'users', :action => 'index', :id => '10'}, set.recognize_path('/users/index/10'))
1802 assert_equal({:controller => 'users', :action => 'index', :id => '10'}, set.recognize_path('/users/index/10/'))
1803 end
1804 end
1805
1806 def test_draw_default_route_with_default_controller
1807 ActionController::Routing.with_controllers(['users']) do
1808 set.draw do |map|
1809 map.connect '/:controller/:action/:id', :controller => 'users'
1810 end
1811 assert_equal({:controller => 'users', :action => 'index'}, set.recognize_path('/'))
1812 end
1813 end
1814
1815 def test_route_with_parameter_shell
1816 ActionController::Routing.with_controllers(['users', 'pages']) do
1817 set.draw do |map|
1818 map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+/
1819 map.connect '/:controller/:action/:id'
1820 end
1821
1822 assert_equal({:controller => 'pages', :action => 'index'}, set.recognize_path('/pages'))
1823 assert_equal({:controller => 'pages', :action => 'index'}, set.recognize_path('/pages/index'))
1824 assert_equal({:controller => 'pages', :action => 'list'}, set.recognize_path('/pages/list'))
1825
1826 assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set.recognize_path('/pages/show/10'))
1827 assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set.recognize_path('/page/10'))
1828 end
1829 end
1830
1831 def test_route_requirements_with_anchor_chars_are_invalid
1832 assert_raise ArgumentError do
1833 set.draw do |map|
1834 map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /^\d+/
1835 end
1836 end
1837 assert_raise ArgumentError do
1838 set.draw do |map|
1839 map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\A\d+/
1840 end
1841 end
1842 assert_raise ArgumentError do
1843 set.draw do |map|
1844 map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+$/
1845 end
1846 end
1847 assert_raise ArgumentError do
1848 set.draw do |map|
1849 map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+\Z/
1850 end
1851 end
1852 assert_raise ArgumentError do
1853 set.draw do |map|
1854 map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+\z/
1855 end
1856 end
1857 assert_nothing_raised do
1858 set.draw do |map|
1859 map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+/, :name => /^(david|jamis)/
1860 end
1861 assert_raise ActionController::RoutingError do
1862 set.generate :controller => 'pages', :action => 'show', :id => 10
1863 end
1864 end
1865 end
1866
1867 def test_route_requirements_with_invalid_http_method_is_invalid
1868 assert_raise ArgumentError do
1869 set.draw do |map|
1870 map.connect 'valid/route', :controller => 'pages', :action => 'show', :conditions => {:method => :invalid}
1871 end
1872 end
1873 end
1874
1875 def test_route_requirements_with_options_method_condition_is_valid
1876 assert_nothing_raised do
1877 set.draw do |map|
1878 map.connect 'valid/route', :controller => 'pages', :action => 'show', :conditions => {:method => :options}
1879 end
1880 end
1881 end
1882
1883 def test_route_requirements_with_head_method_condition_is_invalid
1884 assert_raise ArgumentError do
1885 set.draw do |map|
1886 map.connect 'valid/route', :controller => 'pages', :action => 'show', :conditions => {:method => :head}
1887 end
1888 end
1889 end
1890
1891 def test_non_path_route_requirements_match_all
1892 set.draw do |map|
1893 map.connect 'page/37s', :controller => 'pages', :action => 'show', :name => /(jamis|david)/
1894 end
1895 assert_equal '/page/37s', set.generate(:controller => 'pages', :action => 'show', :name => 'jamis')
1896 assert_raise ActionController::RoutingError do
1897 set.generate(:controller => 'pages', :action => 'show', :name => 'not_jamis')
1898 end
1899 assert_raise ActionController::RoutingError do
1900 set.generate(:controller => 'pages', :action => 'show', :name => 'nor_jamis_and_david')
1901 end
1902 end
1903
1904 def test_recognize_with_encoded_id_and_regex
1905 set.draw do |map|
1906 map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /[a-zA-Z0-9\+]+/
1907 end
1908
1909 assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set.recognize_path('/page/10'))
1910 assert_equal({:controller => 'pages', :action => 'show', :id => 'hello+world'}, set.recognize_path('/page/hello+world'))
1911 end
1912
1913 def test_recognize_with_conditions
1914 Object.const_set(:PeopleController, Class.new)
1915
1916 set.draw do |map|
1917 map.with_options(:controller => "people") do |people|
1918 people.people "/people", :action => "index", :conditions => { :method => :get }
1919 people.connect "/people", :action => "create", :conditions => { :method => :post }
1920 people.person "/people/:id", :action => "show", :conditions => { :method => :get }
1921 people.connect "/people/:id", :action => "update", :conditions => { :method => :put }
1922 people.connect "/people/:id", :action => "destroy", :conditions => { :method => :delete }
1923 end
1924 end
1925
1926 request.path = "/people"
1927 request.env["REQUEST_METHOD"] = "GET"
1928 assert_nothing_raised { set.recognize(request) }
1929 assert_equal("index", request.path_parameters[:action])
1930 request.recycle!
1931
1932 request.env["REQUEST_METHOD"] = "POST"
1933 assert_nothing_raised { set.recognize(request) }
1934 assert_equal("create", request.path_parameters[:action])
1935 request.recycle!
1936
1937 request.env["REQUEST_METHOD"] = "PUT"
1938 assert_nothing_raised { set.recognize(request) }
1939 assert_equal("update", request.path_parameters[:action])
1940 request.recycle!
1941
1942 assert_raise(ActionController::UnknownHttpMethod) {
1943 request.env["REQUEST_METHOD"] = "BACON"
1944 set.recognize(request)
1945 }
1946 request.recycle!
1947
1948 request.path = "/people/5"
1949 request.env["REQUEST_METHOD"] = "GET"
1950 assert_nothing_raised { set.recognize(request) }
1951 assert_equal("show", request.path_parameters[:action])
1952 assert_equal("5", request.path_parameters[:id])
1953 request.recycle!
1954
1955 request.env["REQUEST_METHOD"] = "PUT"
1956 assert_nothing_raised { set.recognize(request) }
1957 assert_equal("update", request.path_parameters[:action])
1958 assert_equal("5", request.path_parameters[:id])
1959 request.recycle!
1960
1961 request.env["REQUEST_METHOD"] = "DELETE"
1962 assert_nothing_raised { set.recognize(request) }
1963 assert_equal("destroy", request.path_parameters[:action])
1964 assert_equal("5", request.path_parameters[:id])
1965 request.recycle!
1966
1967 begin
1968 request.env["REQUEST_METHOD"] = "POST"
1969 set.recognize(request)
1970 flunk 'Should have raised MethodNotAllowed'
1971 rescue ActionController::MethodNotAllowed => e
1972 assert_equal [:get, :put, :delete], e.allowed_methods
1973 end
1974 request.recycle!
1975
1976 ensure
1977 Object.send(:remove_const, :PeopleController)
1978 end
1979
1980 def test_recognize_with_alias_in_conditions
1981 Object.const_set(:PeopleController, Class.new)
1982
1983 set.draw do |map|
1984 map.people "/people", :controller => 'people', :action => "index",
1985 :conditions => { :method => :get }
1986 map.root :people
1987 end
1988
1989 request.path = "/people"
1990 request.env["REQUEST_METHOD"] = "GET"
1991 assert_nothing_raised { set.recognize(request) }
1992 assert_equal("people", request.path_parameters[:controller])
1993 assert_equal("index", request.path_parameters[:action])
1994
1995 request.path = "/"
1996 request.env["REQUEST_METHOD"] = "GET"
1997 assert_nothing_raised { set.recognize(request) }
1998 assert_equal("people", request.path_parameters[:controller])
1999 assert_equal("index", request.path_parameters[:action])
2000 ensure
2001 Object.send(:remove_const, :PeopleController)
2002 end
2003
2004 def test_typo_recognition
2005 Object.const_set(:ArticlesController, Class.new)
2006
2007 set.draw do |map|
2008 map.connect 'articles/:year/:month/:day/:title',
2009 :controller => 'articles', :action => 'permalink',
2010 :year => /\d{4}/, :day => /\d{1,2}/, :month => /\d{1,2}/
2011 end
2012
2013 request.path = "/articles/2005/11/05/a-very-interesting-article"
2014 request.env["REQUEST_METHOD"] = "GET"
2015 assert_nothing_raised { set.recognize(request) }
2016 assert_equal("permalink", request.path_parameters[:action])
2017 assert_equal("2005", request.path_parameters[:year])
2018 assert_equal("11", request.path_parameters[:month])
2019 assert_equal("05", request.path_parameters[:day])
2020 assert_equal("a-very-interesting-article", request.path_parameters[:title])
2021
2022 ensure
2023 Object.send(:remove_const, :ArticlesController)
2024 end
2025
2026 def test_routing_traversal_does_not_load_extra_classes
2027 assert !Object.const_defined?("Profiler__"), "Profiler should not be loaded"
2028 set.draw do |map|
2029 map.connect '/profile', :controller => 'profile'
2030 end
2031
2032 request.path = '/profile'
2033
2034 set.recognize(request) rescue nil
2035
2036 assert !Object.const_defined?("Profiler__"), "Profiler should not be loaded"
2037 end
2038
2039 def test_recognize_with_conditions_and_format
2040 Object.const_set(:PeopleController, Class.new)
2041
2042 set.draw do |map|
2043 map.with_options(:controller => "people") do |people|
2044 people.person "/people/:id", :action => "show", :conditions => { :method => :get }
2045 people.connect "/people/:id", :action => "update", :conditions => { :method => :put }
2046 people.connect "/people/:id.:_format", :action => "show", :conditions => { :method => :get }
2047 end
2048 end
2049
2050 request.path = "/people/5"
2051 request.env["REQUEST_METHOD"] = "GET"
2052 assert_nothing_raised { set.recognize(request) }
2053 assert_equal("show", request.path_parameters[:action])
2054 assert_equal("5", request.path_parameters[:id])
2055 request.recycle!
2056
2057 request.env["REQUEST_METHOD"] = "PUT"
2058 assert_nothing_raised { set.recognize(request) }
2059 assert_equal("update", request.path_parameters[:action])
2060 request.recycle!
2061
2062 request.path = "/people/5.png"
2063 request.env["REQUEST_METHOD"] = "GET"
2064 assert_nothing_raised { set.recognize(request) }
2065 assert_equal("show", request.path_parameters[:action])
2066 assert_equal("5", request.path_parameters[:id])
2067 assert_equal("png", request.path_parameters[:_format])
2068 ensure
2069 Object.send(:remove_const, :PeopleController)
2070 end
2071
2072 def test_generate_with_default_action
2073 set.draw do |map|
2074 map.connect "/people", :controller => "people"
2075 map.connect "/people/list", :controller => "people", :action => "list"
2076 end
2077
2078 url = set.generate(:controller => "people", :action => "list")
2079 assert_equal "/people/list", url
2080 end
2081
2082 def test_root_map
2083 Object.const_set(:PeopleController, Class.new)
2084
2085 set.draw { |map| map.root :controller => "people" }
2086
2087 request.path = ""
2088 request.env["REQUEST_METHOD"] = "GET"
2089 assert_nothing_raised { set.recognize(request) }
2090 assert_equal("people", request.path_parameters[:controller])
2091 assert_equal("index", request.path_parameters[:action])
2092 ensure
2093 Object.send(:remove_const, :PeopleController)
2094 end
2095
2096 def test_namespace
2097 Object.const_set(:Api, Module.new { |m| m.const_set(:ProductsController, Class.new) })
2098
2099 set.draw do |map|
2100
2101 map.namespace 'api' do |api|
2102 api.route 'inventory', :controller => "products", :action => 'inventory'
2103 end
2104
2105 end
2106
2107 request.path = "/api/inventory"
2108 request.env["REQUEST_METHOD"] = "GET"
2109 assert_nothing_raised { set.recognize(request) }
2110 assert_equal("api/products", request.path_parameters[:controller])
2111 assert_equal("inventory", request.path_parameters[:action])
2112 ensure
2113 Object.send(:remove_const, :Api)
2114 end
2115
2116 def test_namespaced_root_map
2117 Object.const_set(:Api, Module.new { |m| m.const_set(:ProductsController, Class.new) })
2118
2119 set.draw do |map|
2120
2121 map.namespace 'api' do |api|
2122 api.root :controller => "products"
2123 end
2124
2125 end
2126
2127 request.path = "/api"
2128 request.env["REQUEST_METHOD"] = "GET"
2129 assert_nothing_raised { set.recognize(request) }
2130 assert_equal("api/products", request.path_parameters[:controller])
2131 assert_equal("index", request.path_parameters[:action])
2132 ensure
2133 Object.send(:remove_const, :Api)
2134 end
2135
2136 def test_namespace_with_path_prefix
2137 Object.const_set(:Api, Module.new { |m| m.const_set(:ProductsController, Class.new) })
2138
2139 set.draw do |map|
2140 map.namespace 'api', :path_prefix => 'prefix' do |api|
2141 api.route 'inventory', :controller => "products", :action => 'inventory'
2142 end
2143 end
2144
2145 request.path = "/prefix/inventory"
2146 request.env["REQUEST_METHOD"] = "GET"
2147 assert_nothing_raised { set.recognize(request) }
2148 assert_equal("api/products", request.path_parameters[:controller])
2149 assert_equal("inventory", request.path_parameters[:action])
2150 ensure
2151 Object.send(:remove_const, :Api)
2152 end
2153
2154 def test_namespace_with_blank_path_prefix
2155 Object.const_set(:Api, Module.new { |m| m.const_set(:ProductsController, Class.new) })
2156
2157 set.draw do |map|
2158 map.namespace 'api', :path_prefix => '' do |api|
2159 api.route 'inventory', :controller => "products", :action => 'inventory'
2160 end
2161 end
2162
2163 request.path = "/inventory"
2164 request.env["REQUEST_METHOD"] = "GET"
2165 assert_nothing_raised { set.recognize(request) }
2166 assert_equal("api/products", request.path_parameters[:controller])
2167 assert_equal("inventory", request.path_parameters[:action])
2168 ensure
2169 Object.send(:remove_const, :Api)
2170 end
2171
2172 def test_generate_finds_best_fit
2173 set.draw do |map|
2174 map.connect "/people", :controller => "people", :action => "index"
2175 map.connect "/ws/people", :controller => "people", :action => "index", :ws => true
2176 end
2177
2178 url = set.generate(:controller => "people", :action => "index", :ws => true)
2179 assert_equal "/ws/people", url
2180 end
2181
2182 def test_generate_changes_controller_module
2183 set.draw { |map| map.connect ':controller/:action/:id' }
2184 current = { :controller => "bling/bloop", :action => "bap", :id => 9 }
2185 url = set.generate({:controller => "foo/bar", :action => "baz", :id => 7}, current)
2186 assert_equal "/foo/bar/baz/7", url
2187 end
2188
2189 def test_id_is_not_impossibly_sticky
2190 set.draw do |map|
2191 map.connect 'foo/:number', :controller => "people", :action => "index"
2192 map.connect ':controller/:action/:id'
2193 end
2194
2195 url = set.generate({:controller => "people", :action => "index", :number => 3},
2196 {:controller => "people", :action => "index", :id => "21"})
2197 assert_equal "/foo/3", url
2198 end
2199
2200 def test_id_is_sticky_when_it_ought_to_be
2201 set.draw do |map|
2202 map.connect ':controller/:id/:action'
2203 end
2204
2205 url = set.generate({:action => "destroy"}, {:controller => "people", :action => "show", :id => "7"})
2206 assert_equal "/people/7/destroy", url
2207 end
2208
2209 def test_use_static_path_when_possible
2210 set.draw do |map|
2211 map.connect 'about', :controller => "welcome", :action => "about"
2212 map.connect ':controller/:action/:id'
2213 end
2214
2215 url = set.generate({:controller => "welcome", :action => "about"},
2216 {:controller => "welcome", :action => "get", :id => "7"})
2217 assert_equal "/about", url
2218 end
2219
2220 def test_generate
2221 set.draw { |map| map.connect ':controller/:action/:id' }
2222
2223 args = { :controller => "foo", :action => "bar", :id => "7", :x => "y" }
2224 assert_equal "/foo/bar/7?x=y", set.generate(args)
2225 assert_equal ["/foo/bar/7", [:x]], set.generate_extras(args)
2226 assert_equal [:x], set.extra_keys(args)
2227 end
2228
2229 def test_generate_with_path_prefix
2230 set.draw { |map| map.connect ':controller/:action/:id', :path_prefix => 'my' }
2231
2232 args = { :controller => "foo", :action => "bar", :id => "7", :x => "y" }
2233 assert_equal "/my/foo/bar/7?x=y", set.generate(args)
2234 end
2235
2236 def test_generate_with_blank_path_prefix
2237 set.draw { |map| map.connect ':controller/:action/:id', :path_prefix => '' }
2238
2239 args = { :controller => "foo", :action => "bar", :id => "7", :x => "y" }
2240 assert_equal "/foo/bar/7?x=y", set.generate(args)
2241 end
2242
2243 def test_named_routes_are_never_relative_to_modules
2244 set.draw do |map|
2245 map.connect "/connection/manage/:action", :controller => 'connection/manage'
2246 map.connect "/connection/connection", :controller => "connection/connection"
2247 map.family_connection "/connection", :controller => "connection"
2248 end
2249
2250 url = set.generate({:controller => "connection"}, {:controller => 'connection/manage'})
2251 assert_equal "/connection/connection", url
2252
2253 url = set.generate({:use_route => :family_connection, :controller => "connection"}, {:controller => 'connection/manage'})
2254 assert_equal "/connection", url
2255 end
2256
2257 def test_action_left_off_when_id_is_recalled
2258 set.draw do |map|
2259 map.connect ':controller/:action/:id'
2260 end
2261 assert_equal '/post', set.generate(
2262 {:controller => 'post', :action => 'index'},
2263 {:controller => 'post', :action => 'show', :id => '10'}
2264 )
2265 end
2266
2267 def test_query_params_will_be_shown_when_recalled
2268 set.draw do |map|
2269 map.connect 'show_post/:parameter', :controller => 'post', :action => 'show'
2270 map.connect ':controller/:action/:id'
2271 end
2272 assert_equal '/post/edit?parameter=1', set.generate(
2273 {:action => 'edit', :parameter => 1},
2274 {:controller => 'post', :action => 'show', :parameter => 1}
2275 )
2276 end
2277
2278 def test_format_is_not_inherit
2279 set.draw do |map|
2280 map.connect '/posts.:format', :controller => 'posts'
2281 end
2282
2283 assert_equal '/posts', set.generate(
2284 {:controller => 'posts'},
2285 {:controller => 'posts', :action => 'index', :format => 'xml'}
2286 )
2287
2288 assert_equal '/posts.xml', set.generate(
2289 {:controller => 'posts', :format => 'xml'},
2290 {:controller => 'posts', :action => 'index', :format => 'xml'}
2291 )
2292 end
2293
2294 def test_expiry_determination_should_consider_values_with_to_param
2295 set.draw { |map| map.connect 'projects/:project_id/:controller/:action' }
2296 assert_equal '/projects/1/post/show', set.generate(
2297 {:action => 'show', :project_id => 1},
2298 {:controller => 'post', :action => 'show', :project_id => '1'})
2299 end
2300
2301 def test_generate_all
2302 set.draw do |map|
2303 map.connect 'show_post/:id', :controller => 'post', :action => 'show'
2304 map.connect ':controller/:action/:id'
2305 end
2306 all = set.generate(
2307 {:action => 'show', :id => 10, :generate_all => true},
2308 {:controller => 'post', :action => 'show'}
2309 )
2310 assert_equal 2, all.length
2311 assert_equal '/show_post/10', all.first
2312 assert_equal '/post/show/10', all.last
2313 end
2314
2315 def test_named_route_in_nested_resource
2316 set.draw do |map|
2317 map.resources :projects do |project|
2318 project.milestones 'milestones', :controller => 'milestones', :action => 'index'
2319 end
2320 end
2321
2322 request.path = "/projects/1/milestones"
2323 request.env["REQUEST_METHOD"] = "GET"
2324 assert_nothing_raised { set.recognize(request) }
2325 assert_equal("milestones", request.path_parameters[:controller])
2326 assert_equal("index", request.path_parameters[:action])
2327 end
2328
2329 def test_setting_root_in_namespace_using_symbol
2330 assert_nothing_raised do
2331 set.draw do |map|
2332 map.namespace :admin do |admin|
2333 admin.root :controller => 'home'
2334 end
2335 end
2336 end
2337 end
2338
2339 def test_setting_root_in_namespace_using_string
2340 assert_nothing_raised do
2341 set.draw do |map|
2342 map.namespace 'admin' do |admin|
2343 admin.root :controller => 'home'
2344 end
2345 end
2346 end
2347 end
2348
2349 def test_route_requirements_with_unsupported_regexp_options_must_error
2350 assert_raise ArgumentError do
2351 set.draw do |map|
2352 map.connect 'page/:name', :controller => 'pages',
2353 :action => 'show',
2354 :requirements => {:name => /(david|jamis)/m}
2355 end
2356 end
2357 end
2358
2359 def test_route_requirements_with_supported_options_must_not_error
2360 assert_nothing_raised do
2361 set.draw do |map|
2362 map.connect 'page/:name', :controller => 'pages',
2363 :action => 'show',
2364 :requirements => {:name => /(david|jamis)/i}
2365 end
2366 end
2367 assert_nothing_raised do
2368 set.draw do |map|
2369 map.connect 'page/:name', :controller => 'pages',
2370 :action => 'show',
2371 :requirements => {:name => / # Desperately overcommented regexp
2372 ( #Either
2373 david #The Creator
2374 | #Or
2375 jamis #The Deployer
2376 )/x}
2377 end
2378 end
2379 end
2380
2381 def test_route_requirement_recognize_with_ignore_case
2382 set.draw do |map|
2383 map.connect 'page/:name', :controller => 'pages',
2384 :action => 'show',
2385 :requirements => {:name => /(david|jamis)/i}
2386 end
2387 assert_equal({:controller => 'pages', :action => 'show', :name => 'jamis'}, set.recognize_path('/page/jamis'))
2388 assert_raise ActionController::RoutingError do
2389 set.recognize_path('/page/davidjamis')
2390 end
2391 assert_equal({:controller => 'pages', :action => 'show', :name => 'DAVID'}, set.recognize_path('/page/DAVID'))
2392 end
2393
2394 def test_route_requirement_generate_with_ignore_case
2395 set.draw do |map|
2396 map.connect 'page/:name', :controller => 'pages',
2397 :action => 'show',
2398 :requirements => {:name => /(david|jamis)/i}
2399 end
2400 url = set.generate({:controller => 'pages', :action => 'show', :name => 'david'})
2401 assert_equal "/page/david", url
2402 assert_raise ActionController::RoutingError do
2403 url = set.generate({:controller => 'pages', :action => 'show', :name => 'davidjamis'})
2404 end
2405 url = set.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'})
2406 assert_equal "/page/JAMIS", url
2407 end
2408
2409 def test_route_requirement_recognize_with_extended_syntax
2410 set.draw do |map|
2411 map.connect 'page/:name', :controller => 'pages',
2412 :action => 'show',
2413 :requirements => {:name => / # Desperately overcommented regexp
2414 ( #Either
2415 david #The Creator
2416 | #Or
2417 jamis #The Deployer
2418 )/x}
2419 end
2420 assert_equal({:controller => 'pages', :action => 'show', :name => 'jamis'}, set.recognize_path('/page/jamis'))
2421 assert_equal({:controller => 'pages', :action => 'show', :name => 'david'}, set.recognize_path('/page/david'))
2422 assert_raise ActionController::RoutingError do
2423 set.recognize_path('/page/david #The Creator')
2424 end
2425 assert_raise ActionController::RoutingError do
2426 set.recognize_path('/page/David')
2427 end
2428 end
2429
2430 def test_route_requirement_generate_with_extended_syntax
2431 set.draw do |map|
2432 map.connect 'page/:name', :controller => 'pages',
2433 :action => 'show',
2434 :requirements => {:name => / # Desperately overcommented regexp
2435 ( #Either
2436 david #The Creator
2437 | #Or
2438 jamis #The Deployer
2439 )/x}
2440 end
2441 url = set.generate({:controller => 'pages', :action => 'show', :name => 'david'})
2442 assert_equal "/page/david", url
2443 assert_raise ActionController::RoutingError do
2444 url = set.generate({:controller => 'pages', :action => 'show', :name => 'davidjamis'})
2445 end
2446 assert_raise ActionController::RoutingError do
2447 url = set.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'})
2448 end
2449 end
2450
2451 def test_route_requirement_generate_with_xi_modifiers
2452 set.draw do |map|
2453 map.connect 'page/:name', :controller => 'pages',
2454 :action => 'show',
2455 :requirements => {:name => / # Desperately overcommented regexp
2456 ( #Either
2457 david #The Creator
2458 | #Or
2459 jamis #The Deployer
2460 )/xi}
2461 end
2462 url = set.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'})
2463 assert_equal "/page/JAMIS", url
2464 end
2465
2466 def test_route_requirement_recognize_with_xi_modifiers
2467 set.draw do |map|
2468 map.connect 'page/:name', :controller => 'pages',
2469 :action => 'show',
2470 :requirements => {:name => / # Desperately overcommented regexp
2471 ( #Either
2472 david #The Creator
2473 | #Or
2474 jamis #The Deployer
2475 )/xi}
2476 end
2477 assert_equal({:controller => 'pages', :action => 'show', :name => 'JAMIS'}, set.recognize_path('/page/JAMIS'))
2478 end
2479 end
2480
2481 class RouteLoadingTest < Test::Unit::TestCase
2482 def setup
2483 routes.instance_variable_set '@routes_last_modified', nil
2484 silence_warnings { Object.const_set :RAILS_ROOT, '.' }
2485 routes.add_configuration_file(File.join(RAILS_ROOT, 'config', 'routes.rb'))
2486
2487 @stat = stub_everything
2488 end
2489
2490 def teardown
2491 ActionController::Routing::Routes.configuration_files.clear
2492 Object.send :remove_const, :RAILS_ROOT
2493 end
2494
2495 def test_load
2496 File.expects(:stat).returns(@stat)
2497 routes.expects(:load).with(regexp_matches(/routes\.rb$/))
2498
2499 routes.reload
2500 end
2501
2502 def test_no_reload_when_not_modified
2503 @stat.expects(:mtime).times(2).returns(1)
2504 File.expects(:stat).times(2).returns(@stat)
2505 routes.expects(:load).with(regexp_matches(/routes\.rb$/)).at_most_once
2506
2507 2.times { routes.reload }
2508 end
2509
2510 def test_reload_when_modified
2511 @stat.expects(:mtime).at_least(2).returns(1, 2)
2512 File.expects(:stat).at_least(2).returns(@stat)
2513 routes.expects(:load).with(regexp_matches(/routes\.rb$/)).times(2)
2514
2515 2.times { routes.reload }
2516 end
2517
2518 def test_bang_forces_reload
2519 @stat.expects(:mtime).at_least(2).returns(1)
2520 File.expects(:stat).at_least(2).returns(@stat)
2521 routes.expects(:load).with(regexp_matches(/routes\.rb$/)).times(2)
2522
2523 2.times { routes.reload! }
2524 end
2525
2526 def test_adding_inflections_forces_reload
2527 ActiveSupport::Inflector::Inflections.instance.expects(:uncountable).with('equipment')
2528 routes.expects(:reload!)
2529
2530 ActiveSupport::Inflector.inflections { |inflect| inflect.uncountable('equipment') }
2531 end
2532
2533 def test_load_with_configuration
2534 routes.configuration_files.clear
2535 routes.add_configuration_file("foobarbaz")
2536 File.expects(:stat).returns(@stat)
2537 routes.expects(:load).with("foobarbaz")
2538
2539 routes.reload
2540 end
2541
2542 def test_load_multiple_configurations
2543 routes.add_configuration_file("engines.rb")
2544
2545 File.expects(:stat).at_least_once.returns(@stat)
2546
2547 routes.expects(:load).with('./config/routes.rb')
2548 routes.expects(:load).with('engines.rb')
2549
2550 routes.reload
2551 end
2552
2553 private
2554 def routes
2555 ActionController::Routing::Routes
2556 end
2557 end