PageRenderTime 48ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/actionpack/test/controller/routing_test.rb

https://github.com/brandondrew/rails
Ruby | 2407 lines | 1955 code | 427 blank | 25 comment | 9 complexity | 581f8075aac683dc8ba6ca0d8107fa5d MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. require 'abstract_unit'
  2. require 'controller/fake_controllers'
  3. require 'action_controller/routing'
  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. RunTimeTests = ARGV.include? 'time'
  10. ROUTING = ActionController::Routing
  11. class ROUTING::RouteBuilder
  12. attr_reader :warn_output
  13. def warn(msg)
  14. (@warn_output ||= []) << msg
  15. end
  16. end
  17. # See RFC 3986, section 3.3 for allowed path characters.
  18. class UriReservedCharactersRoutingTest < Test::Unit::TestCase
  19. def setup
  20. ActionController::Routing.use_controllers! ['controller']
  21. @set = ActionController::Routing::RouteSet.new
  22. @set.draw do |map|
  23. map.connect ':controller/:action/:variable/*additional'
  24. end
  25. safe, unsafe = %w(: @ & = + $ , ;), %w(^ / ? # [ ])
  26. hex = unsafe.map { |char| '%' + char.unpack('H2').first.upcase }
  27. @segment = "#{safe.join}#{unsafe.join}".freeze
  28. @escaped = "#{safe.join}#{hex.join}".freeze
  29. end
  30. def test_route_generation_escapes_unsafe_path_characters
  31. assert_equal "/contr#{@segment}oller/act#{@escaped}ion/var#{@escaped}iable/add#{@escaped}itional-1/add#{@escaped}itional-2",
  32. @set.generate(:controller => "contr#{@segment}oller",
  33. :action => "act#{@segment}ion",
  34. :variable => "var#{@segment}iable",
  35. :additional => ["add#{@segment}itional-1", "add#{@segment}itional-2"])
  36. end
  37. def test_route_recognition_unescapes_path_components
  38. options = { :controller => "controller",
  39. :action => "act#{@segment}ion",
  40. :variable => "var#{@segment}iable",
  41. :additional => ["add#{@segment}itional-1", "add#{@segment}itional-2"] }
  42. assert_equal options, @set.recognize_path("/controller/act#{@escaped}ion/var#{@escaped}iable/add#{@escaped}itional-1/add#{@escaped}itional-2")
  43. end
  44. def test_route_generation_allows_passing_non_string_values_to_generated_helper
  45. assert_equal "/controller/action/variable/1/2", @set.generate(:controller => "controller",
  46. :action => "action",
  47. :variable => "variable",
  48. :additional => [1, 2])
  49. end
  50. end
  51. class SegmentTest < Test::Unit::TestCase
  52. def test_first_segment_should_interpolate_for_structure
  53. s = ROUTING::Segment.new
  54. def s.interpolation_statement(array) 'hello' end
  55. assert_equal 'hello', s.continue_string_structure([])
  56. end
  57. def test_interpolation_statement
  58. s = ROUTING::StaticSegment.new("Hello")
  59. assert_equal "Hello", eval(s.interpolation_statement([]))
  60. assert_equal "HelloHello", eval(s.interpolation_statement([s]))
  61. s2 = ROUTING::StaticSegment.new("-")
  62. assert_equal "Hello-Hello", eval(s.interpolation_statement([s, s2]))
  63. s3 = ROUTING::StaticSegment.new("World")
  64. assert_equal "Hello-World", eval(s3.interpolation_statement([s, s2]))
  65. end
  66. end
  67. class StaticSegmentTest < Test::Unit::TestCase
  68. def test_interpolation_chunk_should_respect_raw
  69. s = ROUTING::StaticSegment.new('Hello World')
  70. assert !s.raw?
  71. assert_equal 'Hello%20World', s.interpolation_chunk
  72. s = ROUTING::StaticSegment.new('Hello World', :raw => true)
  73. assert s.raw?
  74. assert_equal 'Hello World', s.interpolation_chunk
  75. end
  76. def test_regexp_chunk_should_escape_specials
  77. s = ROUTING::StaticSegment.new('Hello*World')
  78. assert_equal 'Hello\*World', s.regexp_chunk
  79. s = ROUTING::StaticSegment.new('HelloWorld')
  80. assert_equal 'HelloWorld', s.regexp_chunk
  81. end
  82. def test_regexp_chunk_should_add_question_mark_for_optionals
  83. s = ROUTING::StaticSegment.new("/", :optional => true)
  84. assert_equal "/?", s.regexp_chunk
  85. s = ROUTING::StaticSegment.new("hello", :optional => true)
  86. assert_equal "(?:hello)?", s.regexp_chunk
  87. end
  88. end
  89. class DynamicSegmentTest < Test::Unit::TestCase
  90. def segment(options = {})
  91. unless @segment
  92. @segment = ROUTING::DynamicSegment.new(:a, options)
  93. end
  94. @segment
  95. end
  96. def test_extract_value
  97. s = ROUTING::DynamicSegment.new(:a)
  98. hash = {:a => '10', :b => '20'}
  99. assert_equal '10', eval(s.extract_value)
  100. hash = {:b => '20'}
  101. assert_equal nil, eval(s.extract_value)
  102. s.default = '20'
  103. assert_equal '20', eval(s.extract_value)
  104. end
  105. def test_default_local_name
  106. assert_equal 'a_value', segment.local_name,
  107. "Unexpected name -- all value_check tests will fail!"
  108. end
  109. def test_presence_value_check
  110. a_value = 10
  111. assert eval(segment.value_check)
  112. end
  113. def test_regexp_value_check_rejects_nil
  114. segment = segment(:regexp => /\d+/)
  115. a_value = nil
  116. assert !eval(segment.value_check)
  117. end
  118. def test_optional_regexp_value_check_should_accept_nil
  119. segment = segment(:regexp => /\d+/, :optional => true)
  120. a_value = nil
  121. assert eval(segment.value_check)
  122. end
  123. def test_regexp_value_check_rejects_no_match
  124. segment = segment(:regexp => /\d+/)
  125. a_value = "Hello20World"
  126. assert !eval(segment.value_check)
  127. a_value = "20Hi"
  128. assert !eval(segment.value_check)
  129. end
  130. def test_regexp_value_check_accepts_match
  131. segment = segment(:regexp => /\d+/)
  132. a_value = "30"
  133. assert eval(segment.value_check)
  134. end
  135. def test_value_check_fails_on_nil
  136. a_value = nil
  137. assert ! eval(segment.value_check)
  138. end
  139. def test_optional_value_needs_no_check
  140. segment = segment(:optional => true)
  141. a_value = nil
  142. assert_equal nil, segment.value_check
  143. end
  144. def test_regexp_value_check_should_accept_match_with_default
  145. segment = segment(:regexp => /\d+/, :default => '200')
  146. a_value = '100'
  147. assert eval(segment.value_check)
  148. end
  149. def test_expiry_should_not_trigger_once_expired
  150. expired = true
  151. hash = merged = {:a => 2, :b => 3}
  152. options = {:b => 3}
  153. expire_on = Hash.new { raise 'No!!!' }
  154. eval(segment.expiry_statement)
  155. rescue RuntimeError
  156. flunk "Expiry check should not have occurred!"
  157. end
  158. def test_expiry_should_occur_according_to_expire_on
  159. expired = false
  160. hash = merged = {:a => 2, :b => 3}
  161. options = {:b => 3}
  162. expire_on = {:b => true, :a => false}
  163. eval(segment.expiry_statement)
  164. assert !expired
  165. assert_equal({:a => 2, :b => 3}, hash)
  166. expire_on = {:b => true, :a => true}
  167. eval(segment.expiry_statement)
  168. assert expired
  169. assert_equal({:b => 3}, hash)
  170. end
  171. def test_extraction_code_should_return_on_nil
  172. hash = merged = {:b => 3}
  173. options = {:b => 3}
  174. a_value = nil
  175. # Local jump because of return inside eval.
  176. assert_raises(LocalJumpError) { eval(segment.extraction_code) }
  177. end
  178. def test_extraction_code_should_return_on_mismatch
  179. segment = segment(:regexp => /\d+/)
  180. hash = merged = {:a => 'Hi', :b => '3'}
  181. options = {:b => '3'}
  182. a_value = nil
  183. # Local jump because of return inside eval.
  184. assert_raises(LocalJumpError) { eval(segment.extraction_code) }
  185. end
  186. def test_extraction_code_should_accept_value_and_set_local
  187. hash = merged = {:a => 'Hi', :b => '3'}
  188. options = {:b => '3'}
  189. a_value = nil
  190. expired = true
  191. eval(segment.extraction_code)
  192. assert_equal 'Hi', a_value
  193. end
  194. def test_extraction_should_work_without_value_check
  195. segment.default = 'hi'
  196. hash = merged = {:b => '3'}
  197. options = {:b => '3'}
  198. a_value = nil
  199. expired = true
  200. eval(segment.extraction_code)
  201. assert_equal 'hi', a_value
  202. end
  203. def test_extraction_code_should_perform_expiry
  204. expired = false
  205. hash = merged = {:a => 'Hi', :b => '3'}
  206. options = {:b => '3'}
  207. expire_on = {:a => true}
  208. a_value = nil
  209. eval(segment.extraction_code)
  210. assert_equal 'Hi', a_value
  211. assert expired
  212. assert_equal options, hash
  213. end
  214. def test_interpolation_chunk_should_replace_value
  215. a_value = 'Hi'
  216. assert_equal a_value, eval(%("#{segment.interpolation_chunk}"))
  217. end
  218. def test_interpolation_chunk_should_accept_nil
  219. a_value = nil
  220. assert_equal '', eval(%("#{segment.interpolation_chunk('a_value')}"))
  221. end
  222. def test_value_regexp_should_be_nil_without_regexp
  223. assert_equal nil, segment.value_regexp
  224. end
  225. def test_value_regexp_should_match_exacly
  226. segment = segment(:regexp => /\d+/)
  227. assert_no_match segment.value_regexp, "Hello 10 World"
  228. assert_no_match segment.value_regexp, "Hello 10"
  229. assert_no_match segment.value_regexp, "10 World"
  230. assert_match segment.value_regexp, "10"
  231. end
  232. def test_regexp_chunk_should_return_string
  233. segment = segment(:regexp => /\d+/)
  234. assert_kind_of String, segment.regexp_chunk
  235. end
  236. def test_build_pattern_non_optional_with_no_captures
  237. # Non optional
  238. a_segment = ROUTING::DynamicSegment.new(nil, :regexp => /\d+/)
  239. assert_equal "(\\d+)stuff", a_segment.build_pattern('stuff')
  240. end
  241. def test_build_pattern_non_optional_with_captures
  242. # Non optional
  243. a_segment = ROUTING::DynamicSegment.new(nil, :regexp => /(\d+)(.*?)/)
  244. assert_equal "((\\d+)(.*?))stuff", a_segment.build_pattern('stuff')
  245. end
  246. def test_optionality_implied
  247. a_segment = ROUTING::DynamicSegment.new(:id)
  248. assert a_segment.optionality_implied?
  249. a_segment = ROUTING::DynamicSegment.new(:action)
  250. assert a_segment.optionality_implied?
  251. end
  252. def test_modifiers_must_be_handled_sensibly
  253. a_segment = ROUTING::DynamicSegment.new(nil, :regexp => /david|jamis/i)
  254. assert_equal "((?i-mx:david|jamis))stuff", a_segment.build_pattern('stuff')
  255. a_segment = ROUTING::DynamicSegment.new(nil, :regexp => /david|jamis/x)
  256. assert_equal "((?x-mi:david|jamis))stuff", a_segment.build_pattern('stuff')
  257. a_segment = ROUTING::DynamicSegment.new(nil, :regexp => /david|jamis/)
  258. assert_equal "(david|jamis)stuff", a_segment.build_pattern('stuff')
  259. end
  260. end
  261. class ControllerSegmentTest < Test::Unit::TestCase
  262. def test_regexp_should_only_match_possible_controllers
  263. ActionController::Routing.with_controllers %w(admin/accounts admin/users account pages) do
  264. cs = ROUTING::ControllerSegment.new :controller
  265. regexp = %r{\A#{cs.regexp_chunk}\Z}
  266. ActionController::Routing.possible_controllers.each do |name|
  267. assert_match regexp, name
  268. assert_no_match regexp, "#{name}_fake"
  269. match = regexp.match name
  270. assert_equal name, match[1]
  271. end
  272. end
  273. end
  274. end
  275. class RouteBuilderTest < Test::Unit::TestCase
  276. def builder
  277. @builder ||= ROUTING::RouteBuilder.new
  278. end
  279. def build(path, options)
  280. builder.build(path, options)
  281. end
  282. def test_options_should_not_be_modified
  283. requirements1 = { :id => /\w+/, :controller => /(?:[a-z](?:-?[a-z]+)*)/ }
  284. requirements2 = requirements1.dup
  285. assert_equal requirements1, requirements2
  286. with_options(:controller => 'folder',
  287. :requirements => requirements2) do |m|
  288. m.build 'folders/new', :action => 'new'
  289. end
  290. assert_equal requirements1, requirements2
  291. end
  292. def test_segment_for_static
  293. segment, rest = builder.segment_for 'ulysses'
  294. assert_equal '', rest
  295. assert_kind_of ROUTING::StaticSegment, segment
  296. assert_equal 'ulysses', segment.value
  297. end
  298. def test_segment_for_action
  299. segment, rest = builder.segment_for ':action'
  300. assert_equal '', rest
  301. assert_kind_of ROUTING::DynamicSegment, segment
  302. assert_equal :action, segment.key
  303. assert_equal 'index', segment.default
  304. end
  305. def test_segment_for_dynamic
  306. segment, rest = builder.segment_for ':login'
  307. assert_equal '', rest
  308. assert_kind_of ROUTING::DynamicSegment, segment
  309. assert_equal :login, segment.key
  310. assert_equal nil, segment.default
  311. assert ! segment.optional?
  312. end
  313. def test_segment_for_with_rest
  314. segment, rest = builder.segment_for ':login/:action'
  315. assert_equal :login, segment.key
  316. assert_equal '/:action', rest
  317. segment, rest = builder.segment_for rest
  318. assert_equal '/', segment.value
  319. assert_equal ':action', rest
  320. segment, rest = builder.segment_for rest
  321. assert_equal :action, segment.key
  322. assert_equal '', rest
  323. end
  324. def test_segments_for
  325. segments = builder.segments_for_route_path '/:controller/:action/:id'
  326. assert_kind_of ROUTING::DividerSegment, segments[0]
  327. assert_equal '/', segments[2].value
  328. assert_kind_of ROUTING::DynamicSegment, segments[1]
  329. assert_equal :controller, segments[1].key
  330. assert_kind_of ROUTING::DividerSegment, segments[2]
  331. assert_equal '/', segments[2].value
  332. assert_kind_of ROUTING::DynamicSegment, segments[3]
  333. assert_equal :action, segments[3].key
  334. assert_kind_of ROUTING::DividerSegment, segments[4]
  335. assert_equal '/', segments[4].value
  336. assert_kind_of ROUTING::DynamicSegment, segments[5]
  337. assert_equal :id, segments[5].key
  338. end
  339. def test_segment_for_action
  340. s, r = builder.segment_for(':action/something/else')
  341. assert_equal '/something/else', r
  342. assert_equal :action, s.key
  343. end
  344. def test_action_default_should_not_trigger_on_prefix
  345. s, r = builder.segment_for ':action_name/something/else'
  346. assert_equal '/something/else', r
  347. assert_equal :action_name, s.key
  348. assert_equal nil, s.default
  349. end
  350. def test_divide_route_options
  351. segments = builder.segments_for_route_path '/cars/:action/:person/:car/'
  352. defaults, requirements = builder.divide_route_options(segments,
  353. :action => 'buy', :person => /\w+/, :car => /\w+/,
  354. :defaults => {:person => nil, :car => nil}
  355. )
  356. assert_equal({:action => 'buy', :person => nil, :car => nil}, defaults)
  357. assert_equal({:person => /\w+/, :car => /\w+/}, requirements)
  358. end
  359. def test_assign_route_options
  360. segments = builder.segments_for_route_path '/cars/:action/:person/:car/'
  361. defaults = {:action => 'buy', :person => nil, :car => nil}
  362. requirements = {:person => /\w+/, :car => /\w+/}
  363. route_requirements = builder.assign_route_options(segments, defaults, requirements)
  364. assert_equal({}, route_requirements)
  365. assert_equal :action, segments[3].key
  366. assert_equal 'buy', segments[3].default
  367. assert_equal :person, segments[5].key
  368. assert_equal %r/\w+/, segments[5].regexp
  369. assert segments[5].optional?
  370. assert_equal :car, segments[7].key
  371. assert_equal %r/\w+/, segments[7].regexp
  372. assert segments[7].optional?
  373. end
  374. def test_assign_route_options_with_anchor_chars
  375. segments = builder.segments_for_route_path '/cars/:action/:person/:car/'
  376. defaults = {:action => 'buy', :person => nil, :car => nil}
  377. requirements = {:person => /\w+/, :car => /^\w+$/}
  378. assert_raises ArgumentError do
  379. route_requirements = builder.assign_route_options(segments, defaults, requirements)
  380. end
  381. requirements[:car] = /[^\/]+/
  382. route_requirements = builder.assign_route_options(segments, defaults, requirements)
  383. end
  384. def test_optional_segments_preceding_required_segments
  385. segments = builder.segments_for_route_path '/cars/:action/:person/:car/'
  386. defaults = {:action => 'buy', :person => nil, :car => "model-t"}
  387. assert builder.assign_route_options(segments, defaults, {}).empty?
  388. 0.upto(1) { |i| assert !segments[i].optional?, "segment #{i} is optional and it shouldn't be" }
  389. assert segments[2].optional?
  390. assert_equal nil, builder.warn_output # should only warn on the :person segment
  391. end
  392. def test_segmentation_of_dot_path
  393. segments = builder.segments_for_route_path '/books/:action.rss'
  394. assert builder.assign_route_options(segments, {}, {}).empty?
  395. assert_equal 6, segments.length # "/", "books", "/", ":action", ".", "rss"
  396. assert !segments.any? { |seg| seg.optional? }
  397. end
  398. def test_segmentation_of_dynamic_dot_path
  399. segments = builder.segments_for_route_path '/books/:action.:format'
  400. assert builder.assign_route_options(segments, {}, {}).empty?
  401. assert_equal 6, segments.length # "/", "books", "/", ":action", ".", ":format"
  402. assert !segments.any? { |seg| seg.optional? }
  403. assert_kind_of ROUTING::DynamicSegment, segments.last
  404. end
  405. def test_assignment_of_default_options
  406. segments = builder.segments_for_route_path '/:controller/:action/:id/'
  407. action, id = segments[-4], segments[-2]
  408. assert_equal :action, action.key
  409. assert_equal :id, id.key
  410. assert ! action.optional?
  411. assert ! id.optional?
  412. builder.assign_default_route_options(segments)
  413. assert_equal 'index', action.default
  414. assert action.optional?
  415. assert id.optional?
  416. end
  417. def test_assignment_of_default_options_respects_existing_defaults
  418. segments = builder.segments_for_route_path '/:controller/:action/:id/'
  419. action, id = segments[-4], segments[-2]
  420. assert_equal :action, action.key
  421. assert_equal :id, id.key
  422. action.default = 'show'
  423. action.is_optional = true
  424. id.default = 'Welcome'
  425. id.is_optional = true
  426. builder.assign_default_route_options(segments)
  427. assert_equal 'show', action.default
  428. assert action.optional?
  429. assert_equal 'Welcome', id.default
  430. assert id.optional?
  431. end
  432. def test_assignment_of_default_options_respects_regexps
  433. segments = builder.segments_for_route_path '/:controller/:action/:id/'
  434. action = segments[-4]
  435. assert_equal :action, action.key
  436. segments[-4] = ROUTING::DynamicSegment.new(:action, :regexp => /show|in/)
  437. builder.assign_default_route_options(segments)
  438. assert_equal nil, action.default
  439. assert ! action.optional?
  440. end
  441. def test_assignment_of_is_optional_when_default
  442. segments = builder.segments_for_route_path '/books/:action.rss'
  443. assert_equal segments[3].key, :action
  444. segments[3].default = 'changes'
  445. builder.ensure_required_segments(segments)
  446. assert ! segments[3].optional?
  447. end
  448. def test_is_optional_is_assigned_to_default_segments
  449. segments = builder.segments_for_route_path '/books/:action'
  450. builder.assign_route_options(segments, {:action => 'index'}, {})
  451. assert_equal segments[3].key, :action
  452. assert segments[3].optional?
  453. assert_kind_of ROUTING::DividerSegment, segments[2]
  454. assert segments[2].optional?
  455. end
  456. # XXX is optional not being set right?
  457. # /blah/:defaulted_segment <-- is the second slash optional? it should be.
  458. def test_route_build
  459. ActionController::Routing.with_controllers %w(users pages) do
  460. r = builder.build '/:controller/:action/:id/', :action => nil
  461. [0, 2, 4].each do |i|
  462. assert_kind_of ROUTING::DividerSegment, r.segments[i]
  463. assert_equal '/', r.segments[i].value
  464. assert r.segments[i].optional? if i > 1
  465. end
  466. assert_kind_of ROUTING::DynamicSegment, r.segments[1]
  467. assert_equal :controller, r.segments[1].key
  468. assert_equal nil, r.segments[1].default
  469. assert_kind_of ROUTING::DynamicSegment, r.segments[3]
  470. assert_equal :action, r.segments[3].key
  471. assert_equal 'index', r.segments[3].default
  472. assert_kind_of ROUTING::DynamicSegment, r.segments[5]
  473. assert_equal :id, r.segments[5].key
  474. assert r.segments[5].optional?
  475. end
  476. end
  477. def test_slashes_are_implied
  478. routes = [
  479. builder.build('/:controller/:action/:id/', :action => nil),
  480. builder.build('/:controller/:action/:id', :action => nil),
  481. builder.build(':controller/:action/:id', :action => nil),
  482. builder.build('/:controller/:action/:id/', :action => nil)
  483. ]
  484. expected = routes.first.segments.length
  485. routes.each_with_index do |route, i|
  486. found = route.segments.length
  487. assert_equal expected, found, "Route #{i + 1} has #{found} segments, expected #{expected}"
  488. end
  489. end
  490. end
  491. class RoutingTest < Test::Unit::TestCase
  492. def test_possible_controllers
  493. true_controller_paths = ActionController::Routing.controller_paths
  494. ActionController::Routing.use_controllers! nil
  495. silence_warnings do
  496. Object.send(:const_set, :RAILS_ROOT, File.dirname(__FILE__) + '/controller_fixtures')
  497. end
  498. ActionController::Routing.controller_paths = [
  499. RAILS_ROOT, RAILS_ROOT + '/app/controllers', RAILS_ROOT + '/vendor/plugins/bad_plugin/lib'
  500. ]
  501. assert_equal ["admin/user", "plugin", "user"], ActionController::Routing.possible_controllers.sort
  502. ensure
  503. if true_controller_paths
  504. ActionController::Routing.controller_paths = true_controller_paths
  505. end
  506. ActionController::Routing.use_controllers! nil
  507. Object.send(:remove_const, :RAILS_ROOT) rescue nil
  508. end
  509. def test_possible_controllers_are_reset_on_each_load
  510. true_possible_controllers = ActionController::Routing.possible_controllers
  511. true_controller_paths = ActionController::Routing.controller_paths
  512. ActionController::Routing.use_controllers! nil
  513. root = File.dirname(__FILE__) + '/controller_fixtures'
  514. ActionController::Routing.controller_paths = []
  515. assert_equal [], ActionController::Routing.possible_controllers
  516. ActionController::Routing.controller_paths = [
  517. root, root + '/app/controllers', root + '/vendor/plugins/bad_plugin/lib'
  518. ]
  519. ActionController::Routing::Routes.load!
  520. assert_equal ["admin/user", "plugin", "user"], ActionController::Routing.possible_controllers.sort
  521. ensure
  522. ActionController::Routing.controller_paths = true_controller_paths
  523. ActionController::Routing.use_controllers! true_possible_controllers
  524. Object.send(:remove_const, :RAILS_ROOT) rescue nil
  525. ActionController::Routing::Routes.clear!
  526. ActionController::Routing::Routes.load_routes!
  527. end
  528. def test_with_controllers
  529. c = %w(admin/accounts admin/users account pages)
  530. ActionController::Routing.with_controllers c do
  531. assert_equal c, ActionController::Routing.possible_controllers
  532. end
  533. end
  534. def test_normalize_unix_paths
  535. 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)
  536. paths = ActionController::Routing.normalize_paths(load_paths)
  537. assert_equal %w(vendor/rails/railties/builtin/rails_info vendor/rails/actionpack/lib app/controllers app/helpers app/models config .bar lib .), paths
  538. end
  539. def test_normalize_windows_paths
  540. 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)
  541. paths = ActionController::Routing.normalize_paths(load_paths)
  542. assert_equal %w(vendor\\rails\\railties\\builtin\\rails_info vendor\\rails\\actionpack\\lib app\\controllers app\\helpers app\\models config .bar lib .), paths
  543. end
  544. def test_routing_helper_module
  545. assert_kind_of Module, ActionController::Routing::Helpers
  546. h = ActionController::Routing::Helpers
  547. c = Class.new
  548. assert ! c.ancestors.include?(h)
  549. ActionController::Routing::Routes.install_helpers c
  550. assert c.ancestors.include?(h)
  551. end
  552. end
  553. uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do
  554. class MockController
  555. attr_accessor :routes
  556. def initialize(routes)
  557. self.routes = routes
  558. end
  559. def url_for(options)
  560. only_path = options.delete(:only_path)
  561. port = options.delete(:port) || 80
  562. port_string = port == 80 ? '' : ":#{port}"
  563. host = options.delete(:host) || "named.route.test"
  564. anchor = "##{options.delete(:anchor)}" if options.key?(:anchor)
  565. path = routes.generate(options)
  566. only_path ? "#{path}#{anchor}" : "http://#{host}#{port_string}#{path}#{anchor}"
  567. end
  568. def request
  569. @request ||= MockRequest.new(:host => "named.route.test", :method => :get)
  570. end
  571. end
  572. class MockRequest
  573. attr_accessor :path, :path_parameters, :host, :subdomains, :domain, :method
  574. def initialize(values={})
  575. values.each { |key, value| send("#{key}=", value) }
  576. if values[:host]
  577. subdomain, self.domain = values[:host].split(/\./, 2)
  578. self.subdomains = [subdomain]
  579. end
  580. end
  581. def protocol
  582. "http://"
  583. end
  584. def host_with_port
  585. (subdomains * '.') + '.' + domain
  586. end
  587. end
  588. class LegacyRouteSetTests < Test::Unit::TestCase
  589. attr_reader :rs
  590. def setup
  591. # These tests assume optimisation is on, so re-enable it.
  592. ActionController::Base.optimise_named_routes = true
  593. @rs = ::ActionController::Routing::RouteSet.new
  594. @rs.draw {|m| m.connect ':controller/:action/:id' }
  595. ActionController::Routing.use_controllers! %w(content admin/user admin/news_feed)
  596. end
  597. def test_default_setup
  598. assert_equal({:controller => "content", :action => 'index'}, rs.recognize_path("/content"))
  599. assert_equal({:controller => "content", :action => 'list'}, rs.recognize_path("/content/list"))
  600. assert_equal({:controller => "content", :action => 'show', :id => '10'}, rs.recognize_path("/content/show/10"))
  601. assert_equal({:controller => "admin/user", :action => 'show', :id => '10'}, rs.recognize_path("/admin/user/show/10"))
  602. assert_equal '/admin/user/show/10', rs.generate(:controller => 'admin/user', :action => 'show', :id => 10)
  603. assert_equal '/admin/user/show', rs.generate({:action => 'show'}, {:controller => 'admin/user', :action => 'list', :id => '10'})
  604. assert_equal '/admin/user/list/10', rs.generate({}, {:controller => 'admin/user', :action => 'list', :id => '10'})
  605. assert_equal '/admin/stuff', rs.generate({:controller => 'stuff'}, {:controller => 'admin/user', :action => 'list', :id => '10'})
  606. assert_equal '/stuff', rs.generate({:controller => '/stuff'}, {:controller => 'admin/user', :action => 'list', :id => '10'})
  607. end
  608. def test_ignores_leading_slash
  609. @rs.draw {|m| m.connect '/:controller/:action/:id'}
  610. test_default_setup
  611. end
  612. def test_time_recognition
  613. # We create many routes to make situation more realistic
  614. @rs = ::ActionController::Routing::RouteSet.new
  615. @rs.draw { |map|
  616. map.frontpage '', :controller => 'search', :action => 'new'
  617. map.resources :videos do |video|
  618. video.resources :comments
  619. video.resource :file, :controller => 'video_file'
  620. video.resource :share, :controller => 'video_shares'
  621. video.resource :abuse, :controller => 'video_abuses'
  622. end
  623. map.resources :abuses, :controller => 'video_abuses'
  624. map.resources :video_uploads
  625. map.resources :video_visits
  626. map.resources :users do |user|
  627. user.resource :settings
  628. user.resources :videos
  629. end
  630. map.resources :channels do |channel|
  631. channel.resources :videos, :controller => 'channel_videos'
  632. end
  633. map.resource :session
  634. map.resource :lost_password
  635. map.search 'search', :controller => 'search'
  636. map.resources :pages
  637. map.connect ':controller/:action/:id'
  638. }
  639. n = 1000
  640. if RunTimeTests
  641. GC.start
  642. rectime = Benchmark.realtime do
  643. n.times do
  644. rs.recognize_path("/videos/1234567", {:method => :get})
  645. rs.recognize_path("/videos/1234567/abuse", {:method => :get})
  646. rs.recognize_path("/users/1234567/settings", {:method => :get})
  647. rs.recognize_path("/channels/1234567", {:method => :get})
  648. rs.recognize_path("/session/new", {:method => :get})
  649. rs.recognize_path("/admin/user/show/10", {:method => :get})
  650. end
  651. end
  652. puts "\n\nRecognition (#{rs.routes.size} routes):"
  653. per_url = rectime / (n * 6)
  654. puts "#{per_url * 1000} ms/url"
  655. puts "#{1 / per_url} url/s\n\n"
  656. end
  657. end
  658. def test_time_generation
  659. n = 5000
  660. if RunTimeTests
  661. GC.start
  662. pairs = [
  663. [{:controller => 'content', :action => 'index'}, {:controller => 'content', :action => 'show'}],
  664. [{:controller => 'content'}, {:controller => 'content', :action => 'index'}],
  665. [{:controller => 'content', :action => 'list'}, {:controller => 'content', :action => 'index'}],
  666. [{:controller => 'content', :action => 'show', :id => '10'}, {:controller => 'content', :action => 'list'}],
  667. [{:controller => 'admin/user', :action => 'index'}, {:controller => 'admin/user', :action => 'show'}],
  668. [{:controller => 'admin/user'}, {:controller => 'admin/user', :action => 'index'}],
  669. [{:controller => 'admin/user', :action => 'list'}, {:controller => 'admin/user', :action => 'index'}],
  670. [{:controller => 'admin/user', :action => 'show', :id => '10'}, {:controller => 'admin/user', :action => 'list'}],
  671. ]
  672. p = nil
  673. gentime = Benchmark.realtime do
  674. n.times do
  675. pairs.each {|(a, b)| rs.generate(a, b)}
  676. end
  677. end
  678. puts "\n\nGeneration (RouteSet): (#{(n * 8)} urls)"
  679. per_url = gentime / (n * 8)
  680. puts "#{per_url * 1000} ms/url"
  681. puts "#{1 / per_url} url/s\n\n"
  682. end
  683. end
  684. def test_route_with_colon_first
  685. rs.draw do |map|
  686. map.connect '/:controller/:action/:id', :action => 'index', :id => nil
  687. map.connect ':url', :controller => 'tiny_url', :action => 'translate'
  688. end
  689. end
  690. def test_route_with_regexp_for_controller
  691. rs.draw do |map|
  692. map.connect ':controller/:admintoken/:action/:id', :controller => /admin\/.+/
  693. map.connect ':controller/:action/:id'
  694. end
  695. assert_equal({:controller => "admin/user", :admintoken => "foo", :action => "index"},
  696. rs.recognize_path("/admin/user/foo"))
  697. assert_equal({:controller => "content", :action => "foo"}, rs.recognize_path("/content/foo"))
  698. assert_equal '/admin/user/foo', rs.generate(:controller => "admin/user", :admintoken => "foo", :action => "index")
  699. assert_equal '/content/foo', rs.generate(:controller => "content", :action => "foo")
  700. end
  701. def test_route_with_regexp_and_dot
  702. rs.draw do |map|
  703. map.connect ':controller/:action/:file',
  704. :controller => /admin|user/,
  705. :action => /upload|download/,
  706. :defaults => {:file => nil},
  707. :requirements => {:file => %r{[^/]+(\.[^/]+)?}}
  708. end
  709. # Without a file extension
  710. assert_equal '/user/download/file',
  711. rs.generate(:controller => "user", :action => "download", :file => "file")
  712. assert_equal(
  713. {:controller => "user", :action => "download", :file => "file"},
  714. rs.recognize_path("/user/download/file"))
  715. # Now, let's try a file with an extension, really a dot (.)
  716. assert_equal '/user/download/file.jpg',
  717. rs.generate(
  718. :controller => "user", :action => "download", :file => "file.jpg")
  719. assert_equal(
  720. {:controller => "user", :action => "download", :file => "file.jpg"},
  721. rs.recognize_path("/user/download/file.jpg"))
  722. end
  723. def test_basic_named_route
  724. rs.add_named_route :home, '', :controller => 'content', :action => 'list'
  725. x = setup_for_named_route
  726. assert_equal("http://named.route.test/",
  727. x.send(:home_url))
  728. end
  729. def test_basic_named_route_with_relative_url_root
  730. rs.add_named_route :home, '', :controller => 'content', :action => 'list'
  731. x = setup_for_named_route
  732. ActionController::Base.relative_url_root = "/foo"
  733. assert_equal("http://named.route.test/foo/",
  734. x.send(:home_url))
  735. assert_equal "/foo/", x.send(:home_path)
  736. ActionController::Base.relative_url_root = nil
  737. end
  738. def test_named_route_with_option
  739. rs.add_named_route :page, 'page/:title', :controller => 'content', :action => 'show_page'
  740. x = setup_for_named_route
  741. assert_equal("http://named.route.test/page/new%20stuff",
  742. x.send(:page_url, :title => 'new stuff'))
  743. end
  744. def test_named_route_with_default
  745. rs.add_named_route :page, 'page/:title', :controller => 'content', :action => 'show_page', :title => 'AboutPage'
  746. x = setup_for_named_route
  747. assert_equal("http://named.route.test/page/AboutRails",
  748. x.send(:page_url, :title => "AboutRails"))
  749. end
  750. def test_named_route_with_nested_controller
  751. rs.add_named_route :users, 'admin/user', :controller => 'admin/user', :action => 'index'
  752. x = setup_for_named_route
  753. assert_equal("http://named.route.test/admin/user",
  754. x.send(:users_url))
  755. end
  756. def test_optimised_named_route_call_never_uses_url_for
  757. rs.add_named_route :users, 'admin/user', :controller => '/admin/user', :action => 'index'
  758. rs.add_named_route :user, 'admin/user/:id', :controller=>'/admin/user', :action=>'show'
  759. x = setup_for_named_route
  760. x.expects(:url_for).never
  761. x.send(:users_url)
  762. x.send(:users_path)
  763. x.send(:user_url, 2, :foo=>"bar")
  764. x.send(:user_path, 3, :bar=>"foo")
  765. end
  766. def test_optimised_named_route_with_host
  767. rs.add_named_route :pages, 'pages', :controller => 'content', :action => 'show_page', :host => 'foo.com'
  768. x = setup_for_named_route
  769. x.expects(:url_for).with(:host => 'foo.com', :only_path => false, :controller => 'content', :action => 'show_page', :use_route => :pages).once
  770. x.send(:pages_url)
  771. end
  772. def setup_for_named_route
  773. klass = Class.new(MockController)
  774. rs.install_helpers(klass)
  775. klass.new(rs)
  776. end
  777. def test_named_route_without_hash
  778. rs.draw do |map|
  779. map.normal ':controller/:action/:id'
  780. end
  781. end
  782. def test_named_route_root
  783. rs.draw do |map|
  784. map.root :controller => "hello"
  785. end
  786. x = setup_for_named_route
  787. assert_equal("http://named.route.test/", x.send(:root_url))
  788. assert_equal("/", x.send(:root_path))
  789. end
  790. def test_named_route_with_regexps
  791. rs.draw do |map|
  792. map.article 'page/:year/:month/:day/:title', :controller => 'page', :action => 'show',
  793. :year => /\d+/, :month => /\d+/, :day => /\d+/
  794. map.connect ':controller/:action/:id'
  795. end
  796. x = setup_for_named_route
  797. # assert_equal(
  798. # {:controller => 'page', :action => 'show', :title => 'hi', :use_route => :article, :only_path => false},
  799. # x.send(:article_url, :title => 'hi')
  800. # )
  801. assert_equal(
  802. "http://named.route.test/page/2005/6/10/hi",
  803. x.send(:article_url, :title => 'hi', :day => 10, :year => 2005, :month => 6)
  804. )
  805. end
  806. def test_changing_controller
  807. assert_equal '/admin/stuff/show/10', rs.generate(
  808. {:controller => 'stuff', :action => 'show', :id => 10},
  809. {:controller => 'admin/user', :action => 'index'}
  810. )
  811. end
  812. def test_paths_escaped
  813. rs.draw do |map|
  814. map.path 'file/*path', :controller => 'content', :action => 'show_file'
  815. map.connect ':controller/:action/:id'
  816. end
  817. # No + to space in URI escaping, only for query params.
  818. results = rs.recognize_path "/file/hello+world/how+are+you%3F"
  819. assert results, "Recognition should have succeeded"
  820. assert_equal ['hello+world', 'how+are+you?'], results[:path]
  821. # Use %20 for space instead.
  822. results = rs.recognize_path "/file/hello%20world/how%20are%20you%3F"
  823. assert results, "Recognition should have succeeded"
  824. assert_equal ['hello world', 'how are you?'], results[:path]
  825. results = rs.recognize_path "/file"
  826. assert results, "Recognition should have succeeded"
  827. assert_equal [], results[:path]
  828. end
  829. def test_paths_slashes_unescaped_with_ordered_parameters
  830. rs.add_named_route :path, '/file/*path', :controller => 'content'
  831. # No / to %2F in URI, only for query params.
  832. x = setup_for_named_route
  833. assert_equal("/file/hello/world", x.send(:path_path, 'hello/world'))
  834. end
  835. def test_non_controllers_cannot_be_matched
  836. rs.draw do |map|
  837. map.connect ':controller/:action/:id'
  838. end
  839. assert_raises(ActionController::RoutingError) { rs.recognize_path("/not_a/show/10") }
  840. end
  841. def test_paths_do_not_accept_defaults
  842. assert_raises(ActionController::RoutingError) do
  843. rs.draw do |map|
  844. map.path 'file/*path', :controller => 'content', :action => 'show_file', :path => %w(fake default)
  845. map.connect ':controller/:action/:id'
  846. end
  847. end
  848. rs.draw do |map|
  849. map.path 'file/*path', :controller => 'content', :action => 'show_file', :path => []
  850. map.connect ':controller/:action/:id'
  851. end
  852. end
  853. def test_should_list_options_diff_when_routing_requirements_dont_match
  854. rs.draw do |map|
  855. map.post 'post/:id', :controller=> 'post', :action=> 'show', :requirements => {:id => /\d+/}
  856. end
  857. exception = assert_raise(ActionController::RoutingError) { rs.generate(:controller => 'post', :action => 'show', :bad_param => "foo", :use_route => "post") }
  858. assert_match /^post_url failed to generate/, exception.message
  859. from_match = exception.message.match(/from \{[^\}]+\}/).to_s
  860. assert_match /:bad_param=>"foo"/, from_match
  861. assert_match /:action=>"show"/, from_match
  862. assert_match /:controller=>"post"/, from_match
  863. expected_match = exception.message.match(/expected: \{[^\}]+\}/).to_s
  864. assert_no_match /:bad_param=>"foo"/, expected_match
  865. assert_match /:action=>"show"/, expected_match
  866. assert_match /:controller=>"post"/, expected_match
  867. diff_match = exception.message.match(/diff: \{[^\}]+\}/).to_s
  868. assert_match /:bad_param=>"foo"/, diff_match
  869. assert_no_match /:action=>"show"/, diff_match
  870. assert_no_match /:controller=>"post"/, diff_match
  871. end
  872. # this specifies the case where your formerly would get a very confusing error message with an empty diff
  873. def test_should_have_better_error_message_when_options_diff_is_empty
  874. rs.draw do |map|
  875. map.content '/content/:query', :controller => 'content', :action => 'show'
  876. end
  877. exception = assert_raise(ActionController::RoutingError) { rs.generate(:controller => 'content', :action => 'show', :use_route => "content") }
  878. assert_match %r[:action=>"show"], exception.message
  879. assert_match %r[:controller=>"content"], exception.message
  880. assert_match %r[you may have ambiguous routes, or you may need to supply additional parameters for this route], exception.message
  881. assert_match %r[content_url has the following required parameters: \["content", :query\] - are they all satisfied?], exception.message
  882. end
  883. def test_dynamic_path_allowed
  884. rs.draw do |map|
  885. map.connect '*path', :controller => 'content', :action => 'show_file'
  886. end
  887. assert_equal '/pages/boo', rs.generate(:controller => 'content', :action => 'show_file', :path => %w(pages boo))
  888. end
  889. def test_dynamic_recall_paths_allowed
  890. rs.draw do |map|
  891. map.connect '*path', :controller => 'content', :action => 'show_file'
  892. end
  893. recall_path = ActionController::Routing::PathSegment::Result.new(%w(pages boo))
  894. assert_equal '/pages/boo', rs.generate({}, :controller => 'content', :action => 'show_file', :path => recall_path)
  895. end
  896. def test_backwards
  897. rs.draw do |map|
  898. map.connect 'page/:id/:action', :controller => 'pages', :action => 'show'
  899. map.connect ':controller/:action/:id'
  900. end
  901. assert_equal '/page/20', rs.generate({:id => 20}, {:controller => 'pages', :action => 'show'})
  902. assert_equal '/page/20', rs.generate(:controller => 'pages', :id => 20, :action => 'show')
  903. assert_equal '/pages/boo', rs.generate(:controller => 'pages', :action => 'boo')
  904. end
  905. def test_route_with_fixnum_default
  906. rs.draw do |map|
  907. map.connect 'page/:id', :controller => 'content', :action => 'show_page', :id => 1
  908. map.connect ':controller/:action/:id'
  909. end
  910. assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page')
  911. assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page', :id => 1)
  912. assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page', :id => '1')
  913. assert_equal '/page/10', rs.generate(:controller => 'content', :action => 'show_page', :id => 10)
  914. assert_equal({:controller => "content", :action => 'show_page', :id => '1'}, rs.recognize_path("/page"))
  915. assert_equal({:controller => "content", :action => 'show_page', :id => '1'}, rs.recognize_path("/page/1"))
  916. assert_equal({:controller => "content", :action => 'show_page', :id => '10'}, rs.recognize_path("/page/10"))
  917. end
  918. # For newer revision
  919. def test_route_with_text_default
  920. rs.draw do |map|
  921. map.connect 'page/:id', :controller => 'content', :action => 'show_page', :id => 1
  922. map.connect ':controller/:action/:id'
  923. end
  924. assert_equal '/page/foo', rs.generate(:controller => 'content', :action => 'show_page', :id => 'foo')
  925. assert_equal({:controller => "content", :action => 'show_page', :id => 'foo'}, rs.recognize_path("/page/foo"))
  926. token = "\321\202\320\265\320\272\321\201\321\202" # 'text' in russian
  927. escaped_token = CGI::escape(token)
  928. assert_equal '/page/' + escaped_token, rs.generate(:controller => 'content', :action => 'show_page', :id => token)
  929. assert_equal({:controller => "content", :action => 'show_page', :id => token}, rs.recognize_path("/page/#{escaped_token}"))
  930. end
  931. def test_action_expiry
  932. assert_equal '/content', rs.generate({:controller => 'content'}, {:controller => 'content', :action => 'show'})
  933. end
  934. def test_recognition_with_uppercase_controller_name
  935. assert_equal({:controller => "content", :action => 'index'}, rs.recognize_path("/Content"))
  936. assert_equal({:controller => "content", :action => 'list'}, rs.recognize_path("/ConTent/list"))
  937. assert_equal({:controller => "content", :action => 'show', :id => '10'}, rs.recognize_path("/CONTENT/show/10"))
  938. # these used to work, before the routes rewrite, but support for this was pulled in the new version...
  939. #assert_equal({'controller' => "admin/news_feed", 'action' => 'index'}, rs.recognize_path("Admin/NewsFeed"))
  940. #assert_equal({'controller' => "admin/news_feed", 'action' => 'index'}, rs.recognize_path("Admin/News_Feed"))
  941. end
  942. def test_requirement_should_prevent_optional_id
  943. rs.draw do |map|
  944. map.post 'post/:id', :controller=> 'post', :action=> 'show', :requirements => {:id => /\d+/}
  945. end
  946. assert_equal '/post/10', rs.generate(:controller => 'post', :action => 'show', :id => 10)
  947. assert_raises ActionController::RoutingError do
  948. rs.generate(:controller => 'post', :action => 'show')
  949. end
  950. end
  951. def test_both_requirement_and_optional
  952. rs.draw do |map|
  953. map.blog('test/:year', :controller => 'post', :action => 'show',
  954. :defaults => { :year => nil },
  955. :requirements => { :year => /\d{4}/ }
  956. )
  957. map.connect ':controller/:action/:id'
  958. end
  959. assert_equal '/test', rs.generate(:controller => 'post', :action => 'show')
  960. assert_equal '/test', rs.generate(:controller => 'post', :action => 'show', :year => nil)
  961. x = setup_for_named_route
  962. assert_equal("http://named.route.test/test",
  963. x.send(:blog_url))
  964. end
  965. def test_set_to_nil_forgets
  966. rs.draw do |map|
  967. map.connect 'pages/:year/:month/:day', :controller => 'content', :action => 'list_pages', :month => nil, :day => nil
  968. map.connect ':controller/:action/:id'
  969. end
  970. assert_equal '/pages/2005',
  971. rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005)
  972. assert_equal '/pages/2005/6',
  973. rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005, :month => 6)
  974. assert_equal '/pages/2005/6/12',
  975. rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005, :month => 6, :day => 12)
  976. assert_equal '/pages/2005/6/4',
  977. rs.generate({:day => 4}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'})
  978. assert_equal '/pages/2005/6',
  979. rs.generate({:day => nil}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'})
  980. assert_equal '/pages/2005',
  981. rs.generate({:day => nil, :month => nil}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'})
  982. end
  983. def test_url_with_no_action_specified
  984. rs.draw do |map|
  985. map.connect '', :controller => 'content'
  986. map.connect ':controller/:action/:id'
  987. end
  988. assert_equal '/', rs.generate(:controller => 'content', :action => 'index')
  989. assert_equal '/', rs.generate(:controller => 'content')
  990. end
  991. def test_named_url_with_no_action_specified
  992. rs.draw do |map|
  993. map.home '', :controller => 'content'
  994. map.connect ':controller/:action/:id'
  995. end
  996. assert_equal '/', rs.generate(:controller => 'content', :action => 'index')
  997. assert_equal '/', rs.generate(:controller => 'content')
  998. x = setup_for_named_route
  999. assert_equal("http://named.route.test/",
  1000. x.send(:home_url))
  1001. end
  1002. def test_url_generated_when_forgetting_action
  1003. [{:controller => 'content', :action => 'index'}, {:controller => 'content'}].each do |hash|
  1004. rs.draw do |map|
  1005. map.home '', hash
  1006. map.connect ':controller/:action/:id'
  1007. end
  1008. assert_equal '/', rs.generate({:action => nil}, {:controller => 'content', :action => 'hello'})
  1009. assert_equal '/', rs.generate({:controller => 'content'})
  1010. assert_equal '/content/hi', rs.generate({:controller => 'content', :action => 'hi'})
  1011. end
  1012. end
  1013. def test_named_route_method
  1014. rs.draw do |map|
  1015. map.categories 'categories', :controller => 'content', :action => 'categories'
  1016. map.connect ':controller/:action/:id'
  1017. end
  1018. assert_equal '/categories', rs.generate(:controller => 'content', :action => 'categories')
  1019. assert_equal '/content/hi', rs.generate({:controller => 'content', :action => 'hi'})
  1020. end
  1021. def test_named_routes_array
  1022. test_named_route_method
  1023. assert_equal [:categories], rs.named_routes.names
  1024. end
  1025. def test_nil_defaults
  1026. rs.draw do |map|
  1027. map.connect 'journal',
  1028. :controller => 'content',
  1029. :action => 'list_journal',
  1030. :date => nil, :user_id => nil
  1031. map.connect ':controller/:action/:id'
  1032. end
  1033. assert_equal '/journal', rs.generate(:controller => 'content', :action => 'list_journal', :date => nil, :user_id => nil)
  1034. end
  1035. def setup_request_method_routes_for(method)
  1036. @request = ActionController::TestRequest.new
  1037. @request.env["REQUEST_METHOD"] = method
  1038. @request.request_uri = "/match"
  1039. rs.draw do |r|
  1040. r.connect '/match', :controller => 'books', :action => 'get', :conditions => { :method => :get }
  1041. r.connect '/match', :controller => 'books', :action => 'post', :conditions => { :method => :post }
  1042. r.connect '/match', :controller => 'books', :action => 'put', :conditions => { :method => :put }
  1043. r.connect '/match', :controller => 'books', :action => 'delete', :conditions => { :method => :delete }
  1044. end
  1045. end
  1046. %w(GET POST PUT DELETE).each do |request_method|
  1047. define_method("test_request_method_recognized_with_#{request_method}") do
  1048. begin
  1049. Object.const_set(:BooksController, Class.new(ActionController::Base))
  1050. setup_request_method_routes_for(request_method)
  1051. assert_nothing_raised { rs.recognize(@request) }
  1052. assert_equal request_method.downcase, @request.path_parameters[:action]
  1053. ensure
  1054. Object.send(:remove_const, :BooksController) rescue nil
  1055. end
  1056. end
  1057. end
  1058. def test_recognize_array_of_methods
  1059. Object.const_set(:BooksController, Class.new(ActionController::Base))
  1060. rs.draw do |r|
  1061. r.connect '/match', :controller => 'books', :action => 'get_or_post', :conditions => { :method => [:get, :post] }
  1062. r.connect '/match', :controller => 'books', :action => 'not_get_or_post'
  1063. end
  1064. @request = ActionController::TestRequest.new
  1065. @request.env["REQUEST_METHOD"] = 'POST'
  1066. @request.request_uri = "/match"
  1067. assert_nothing_raised { rs.recognize(@request) }
  1068. assert_equal 'get_or_post', @request.path_parameters[:action]
  1069. # have to recreate or else the RouteSet uses a cached version:
  1070. @request = ActionController::TestRequest.new
  1071. @request.env["REQUEST_METHOD"] = 'PUT'
  1072. @request.request_uri = "/match"
  1073. assert_nothing_raised { rs.recognize(@request) }
  1074. assert_equal 'not_get_or_post', @request.path_parameters[:action]
  1075. ensure
  1076. Object.send(:remove_const, :BooksController) rescue nil
  1077. end
  1078. def test_subpath_recognized
  1079. Object.const_set(:SubpathBooksController, Class.new(ActionController::Base))
  1080. rs.draw do |r|
  1081. r.connect '/books/:id/edit', :controller => 'subpath_books', :action => 'edit'
  1082. r.connect '/items/:id/:action', :controller => 'subpath_books'
  1083. r.connect '/posts/new/:action', :controller => 'subpath_books'
  1084. r.connect '/posts/:id', :controller => 'subpath_books', :action => "show"
  1085. end
  1086. hash = rs.recognize_path "/books/17/edit"
  1087. assert_not_nil hash
  1088. assert_equal %w(subpath_books 17 edit), [hash[:controller], hash[:id], hash[:action]]
  1089. hash = rs.recognize_path "/items/3/complete"
  1090. assert_not_nil hash
  1091. assert_equal %w(subpath_books 3 complete), [hash[:controller], hash[:id], hash[:action]]
  1092. hash = rs.recognize_path "/posts/new/preview"
  1093. assert_not_nil hash
  1094. assert_equal %w(subpath_books preview), [hash[:controller], hash[:action]

Large files files are truncated, but you can click here to view the full file