diff options
Diffstat (limited to 'actionpack/test/controller')
49 files changed, 2141 insertions, 1909 deletions
diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb index 53cdd358b4..7f3d943bba 100644 --- a/actionpack/test/controller/action_pack_assertions_test.rb +++ b/actionpack/test/controller/action_pack_assertions_test.rb @@ -2,34 +2,26 @@ require 'abstract_unit' require 'action_controller/vendor/html-scanner' require 'controller/fake_controllers' -# a controller class to facilitate the tests class ActionPackAssertionsController < ActionController::Base - # this does absolutely nothing def nothing() head :ok end - # a standard template def hello_world() render :template => "test/hello_world"; end - # a standard template def hello_xml_world() render :template => "test/hello_xml_world"; end - # a standard template rendering PDF def hello_xml_world_pdf self.content_type = "application/pdf" render :template => "test/hello_xml_world" end - # a standard template rendering PDF def hello_xml_world_pdf_header response.headers["Content-Type"] = "application/pdf; charset=utf-8" render :template => "test/hello_xml_world" end - # a standard partial def partial() render :partial => 'test/partial'; end - # a redirect to an internal location def redirect_internal() redirect_to "/nothing"; end def redirect_to_action() redirect_to :action => "flash_me", :id => 1, :params => { "panda" => "fun" }; end @@ -40,33 +32,28 @@ class ActionPackAssertionsController < ActionController::Base def redirect_to_path() redirect_to '/some/path' end + def redirect_invalid_external_route() redirect_to 'ht_tp://www.rubyonrails.org' end + def redirect_to_named_route() redirect_to route_one_url end - # a redirect to an external location def redirect_external() redirect_to "http://www.rubyonrails.org"; end - # a 404 def response404() head '404 AWOL' end - # a 500 def response500() head '500 Sorry' end - # a fictional 599 def response599() head '599 Whoah!' end - # putting stuff in the flash def flash_me flash['hello'] = 'my name is inigo montoya...' render :text => "Inconceivable!" end - # we have a flash, but nothing is in it def flash_me_naked flash.clear render :text => "wow!" end - # assign some template instance variables def assign_this @howdy = "ho" render :inline => "Mr. Henke" @@ -84,61 +71,20 @@ class ActionPackAssertionsController < ActionController::Base render :text => "Hello!", :content_type => Mime::RSS end - # puts something in the session def session_stuffing session['xmas'] = 'turkey' render :text => "ho ho ho" end - # raises exception on get requests - def raise_on_get + def raise_exception_on_get raise "get" if request.get? render :text => "request method: #{request.env['REQUEST_METHOD']}" end - # raises exception on post requests - def raise_on_post + def raise_exception_on_post raise "post" if request.post? render :text => "request method: #{request.env['REQUEST_METHOD']}" end - - def get_valid_record - @record = Class.new do - def valid? - true - end - - def errors - Class.new do - def full_messages; []; end - end.new - end - - end.new - - render :nothing => true - end - - - def get_invalid_record - @record = Class.new do - - def valid? - false - end - - def errors - Class.new do - def full_messages; ['...stuff...']; end - end.new - end - end.new - - render :nothing => true - end - - # 911 - def rescue_action(e) raise; end end # Used to test that assert_response includes the exception message @@ -181,48 +127,39 @@ module Admin end end -# require "action_dispatch/test_process" - -# a test case to exercise the new capabilities TestRequest & TestResponse class ActionPackAssertionsControllerTest < ActionController::TestCase - # -- assertion-based testing ------------------------------------------------ def test_assert_tag_and_url_for get :render_url assert_tag :content => "/action_pack_assertions/flash_me" end - # test the get method, make sure the request really was a get - def test_get - assert_raise(RuntimeError) { get :raise_on_get } - get :raise_on_post + def test_get_request + assert_raise(RuntimeError) { get :raise_exception_on_get } + get :raise_exception_on_post assert_equal @response.body, 'request method: GET' end - # test the get method, make sure the request really was a get - def test_post - assert_raise(RuntimeError) { post :raise_on_post } - post :raise_on_get + def test_post_request + assert_raise(RuntimeError) { post :raise_exception_on_post } + post :raise_exception_on_get + assert_equal @response.body, 'request method: POST' + end + + def test_get_post_request_switch + post :raise_exception_on_get + assert_equal @response.body, 'request method: POST' + get :raise_exception_on_post + assert_equal @response.body, 'request method: GET' + post :raise_exception_on_get assert_equal @response.body, 'request method: POST' + get :raise_exception_on_post + assert_equal @response.body, 'request method: GET' end -# the following test fails because the request_method is now cached on the request instance -# test the get/post switch within one test action -# def test_get_post_switch -# post :raise_on_get -# assert_equal @response.body, 'request method: POST' -# get :raise_on_post -# assert_equal @response.body, 'request method: GET' -# post :raise_on_get -# assert_equal @response.body, 'request method: POST' -# get :raise_on_post -# assert_equal @response.body, 'request method: GET' -# end - - # test the redirection to a named route - def test_assert_redirect_to_named_route + def test_redirect_to_named_route with_routing do |set| - set.draw do |map| + set.draw do match 'route_one', :to => 'action_pack_assertions#nothing', :as => :route_one match ':controller/:action' end @@ -234,9 +171,17 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase end end + def test_string_constraint + with_routing do |set| + set.draw do + match "photos", :to => 'action_pack_assertions#nothing', :constraints => {:subdomain => "admin"} + end + end + end + def test_assert_redirect_to_named_route_failure with_routing do |set| - set.draw do |map| + set.draw do match 'route_one', :to => 'action_pack_assertions#nothing', :as => :route_one match 'route_two', :to => 'action_pack_assertions#nothing', :id => 'two', :as => :route_two match ':controller/:action' @@ -258,10 +203,9 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase @controller = Admin::InnerModuleController.new with_routing do |set| - set.draw do |map| + set.draw do match 'admin/inner_module', :to => 'admin/inner_module#index', :as => :admin_inner_module - # match ':controller/:action' - map.connect ':controller/:action/:id' + match ':controller/:action' end process :redirect_to_index # redirection is <{"action"=>"index", "controller"=>"admin/admin/inner_module"}> @@ -273,10 +217,9 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase @controller = Admin::InnerModuleController.new with_routing do |set| - set.draw do |map| + set.draw do match '/action_pack_assertions/:id', :to => 'action_pack_assertions#index', :as => :top_level - # match ':controller/:action' - map.connect ':controller/:action/:id' + match ':controller/:action' end process :redirect_to_top_level_named_route # assert_redirected_to "http://test.host/action_pack_assertions/foo" would pass because of exact match early return @@ -288,11 +231,10 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase @controller = Admin::InnerModuleController.new with_routing do |set| - set.draw do |map| + set.draw do # this controller exists in the admin namespace as well which is the only difference from previous test match '/user/:id', :to => 'user#index', :as => :top_level - # match ':controller/:action' - map.connect ':controller/:action/:id' + match ':controller/:action' end process :redirect_to_top_level_named_route # assert_redirected_to top_level_url('foo') would pass because of exact match early return @@ -300,53 +242,44 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase end end - # -- standard request/response object testing -------------------------------- - - # make sure that the template objects exist - def test_template_objects_alive + def test_template_objects_exist process :assign_this - assert !@controller.instance_variable_get(:"@hi") + assert !@controller.instance_variable_defined?(:"@hi") assert @controller.instance_variable_get(:"@howdy") end - # make sure we don't have template objects when we shouldn't - def test_template_object_missing + def test_template_objects_missing process :nothing - assert_nil @controller.instance_variable_get(:@howdy) + assert !@controller.instance_variable_defined?(:@howdy) end - # check the empty flashing - def test_flash_me_naked + def test_empty_flash process :flash_me_naked - assert_deprecated do - assert !@response.has_flash? - assert !@response.has_flash_with_contents? - end + assert flash.empty? end - # check if we have flash objects - def test_flash_haves + def test_flash_exist process :flash_me - assert_deprecated do - assert @response.has_flash? - assert @response.has_flash_with_contents? - assert @response.has_flash_object?('hello') - end + assert flash.any? + assert_present flash['hello'] end - # ensure we don't have flash objects - def test_flash_have_nots + def test_flash_does_not_exist process :nothing - assert_deprecated do - assert !@response.has_flash? - assert !@response.has_flash_with_contents? - assert_nil @response.flash['hello'] - end + assert flash.empty? end + def test_session_exist + process :session_stuffing + assert_equal session['xmas'], 'turkey' + end - # check if we were rendered by a file-based template? - def test_rendered_action + def session_does_not_exist + process :nothing + assert session.empty? + end + + def test_render_template_action process :nothing assert_template nil @@ -354,7 +287,6 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase assert_template 'hello_world' end - # check the redirection location def test_redirection_location process :redirect_internal assert_equal 'http://test.host/nothing', @response.redirect_url @@ -368,7 +300,6 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase assert_nil @response.redirect_url end - # check server errors def test_server_error_response_code process :response500 assert @response.server_error? @@ -380,31 +311,23 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase assert !@response.server_error? end - # check a 404 response code def test_missing_response_code process :response404 assert @response.missing? end - # check client errors def test_client_error_response_code process :response404 assert @response.client_error? end - # check to see if our redirection matches a pattern def test_redirect_url_match process :redirect_external assert @response.redirect? - assert_deprecated do - assert @response.redirect_url_match?("rubyonrails") - assert @response.redirect_url_match?(/rubyonrails/) - assert !@response.redirect_url_match?("phpoffrails") - assert !@response.redirect_url_match?(/perloffrails/) - end + assert_match(/rubyonrails/, @response.redirect_url) + assert !/perloffrails/.match(@response.redirect_url) end - # check for a redirection def test_redirection process :redirect_internal assert @response.redirect? @@ -416,14 +339,12 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase assert !@response.redirect? end - # check a successful response code def test_successful_response_code process :nothing assert @response.success? end - # a basic check to make sure we have a TestResponse object - def test_has_response + def test_response_object process :nothing assert_kind_of ActionController::TestResponse, @response end @@ -457,6 +378,11 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase end end + def test_redirect_invalid_external_route + process :redirect_invalid_external_route + assert_redirected_to "http://test.hostht_tp://www.rubyonrails.org" + end + def test_redirected_to_url_full_url process :redirect_to_path assert_redirected_to 'http://test.host/some/path' @@ -547,6 +473,14 @@ class AssertTemplateTest < ActionController::TestCase assert_template :hello_planet end end + + def test_assert_template_reset_between_requests + get :hello_world + assert_template 'test/hello_world' + + get :nothing + assert_template nil + end end class ActionPackHeaderTest < ActionController::TestCase diff --git a/actionpack/test/controller/assert_select_test.rb b/actionpack/test/controller/assert_select_test.rb index 4f8ad23174..f63321c78b 100644 --- a/actionpack/test/controller/assert_select_test.rb +++ b/actionpack/test/controller/assert_select_test.rb @@ -15,10 +15,8 @@ class AssertSelectTest < ActionController::TestCase class AssertSelectMailer < ActionMailer::Base def test(html) - recipients "test <test@test.host>" - from "test@test.host" - subject "Test e-mail" - part :content_type=>"text/html", :body=>html + mail :body => html, :content_type => "text/html", + :subject => "Test e-mail", :from => "test@test.host", :to => "test <test@test.host>" end end @@ -257,7 +255,7 @@ class AssertSelectTest < ActionController::TestCase end assert_raise(Assertion) {assert_select_rjs :insert, :top, "test2"} end - + def test_assert_select_rjs_for_redirect_to render_rjs do |page| page.redirect_to '/' @@ -461,8 +459,8 @@ class AssertSelectTest < ActionController::TestCase assert_select_rjs :remove, "test1" - rescue Assertion - assert_equal "No RJS statement that removes 'test1' was rendered.", $!.message + rescue Assertion => e + assert_equal "No RJS statement that removes 'test1' was rendered.", e.message end def test_assert_select_rjs_for_remove_ignores_block @@ -493,8 +491,8 @@ class AssertSelectTest < ActionController::TestCase assert_select_rjs :show, "test1" - rescue Assertion - assert_equal "No RJS statement that shows 'test1' was rendered.", $!.message + rescue Assertion => e + assert_equal "No RJS statement that shows 'test1' was rendered.", e.message end def test_assert_select_rjs_for_show_ignores_block @@ -525,8 +523,8 @@ class AssertSelectTest < ActionController::TestCase assert_select_rjs :hide, "test1" - rescue Assertion - assert_equal "No RJS statement that hides 'test1' was rendered.", $!.message + rescue Assertion => e + assert_equal "No RJS statement that hides 'test1' was rendered.", e.message end def test_assert_select_rjs_for_hide_ignores_block @@ -557,8 +555,8 @@ class AssertSelectTest < ActionController::TestCase assert_select_rjs :toggle, "test1" - rescue Assertion - assert_equal "No RJS statement that toggles 'test1' was rendered.", $!.message + rescue Assertion => e + assert_equal "No RJS statement that toggles 'test1' was rendered.", e.message end def test_assert_select_rjs_for_toggle_ignores_block @@ -731,7 +729,7 @@ EOF end def render_rjs(&block) - @controller.response_with &block + @controller.response_with(&block) get :rjs end diff --git a/actionpack/test/controller/base_test.rb b/actionpack/test/controller/base_test.rb index ae270b751e..9c22a4e7e0 100644 --- a/actionpack/test/controller/base_test.rb +++ b/actionpack/test/controller/base_test.rb @@ -87,7 +87,7 @@ class RecordIdentifierController < ActionController::Base end class ControllerClassTests < ActiveSupport::TestCase - + def test_controller_path assert_equal 'empty', EmptyController.controller_path assert_equal EmptyController.controller_path, EmptyController.new.controller_path @@ -99,20 +99,6 @@ class ControllerClassTests < ActiveSupport::TestCase assert_equal 'empty', EmptyController.controller_name assert_equal 'contained_empty', Submodule::ContainedEmptyController.controller_name end - - def test_filter_parameter_logging - parameters = [] - config = mock(:config => mock(:filter_parameters => parameters)) - Rails.expects(:application).returns(config) - - assert_deprecated do - Class.new(ActionController::Base) do - filter_parameter_logging :password - end - end - - assert_equal [:password], parameters - end def test_record_identifier assert_respond_to RecordIdentifierController.new, :dom_id @@ -164,15 +150,15 @@ class PerformActionTest < ActionController::TestCase rescue_action_in_public! end - + def test_process_should_be_precise use_controller EmptyController exception = assert_raise AbstractController::ActionNotFound do get :non_existent end - assert_equal exception.message, "The action 'non_existent' could not be found for EmptyController" + assert_equal exception.message, "The action 'non_existent' could not be found for EmptyController" end - + def test_get_on_priv_should_show_selector use_controller MethodMissingController get :shouldnt_be_called @@ -224,7 +210,7 @@ class UrlOptionsTest < ActionController::TestCase assert_equal 'http://www.override.com/from_view?locale=en', @controller.send(:from_view_url) assert_equal 'http://www.override.com/default_url_options/new?locale=en', @controller.url_for(:controller => 'default_url_options') end - end + end def test_url_helpers_does_not_become_actions with_routing do |set| @@ -308,7 +294,7 @@ class EmptyUrlOptionsTest < ActionController::TestCase @controller.request = @request with_routing do |set| - set.draw do |map| + set.draw do resources :things end diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb index c161bea945..01f3e8f2b6 100644 --- a/actionpack/test/controller/caching_test.rb +++ b/actionpack/test/controller/caching_test.rb @@ -16,6 +16,7 @@ end class PageCachingTestController < CachingController caches_page :ok, :no_content, :if => Proc.new { |c| !c.request.format.json? } caches_page :found, :not_found + caches_page :about_me def ok @@ -47,6 +48,14 @@ class PageCachingTestController < CachingController def trailing_slash render :text => "Sneak attack" end + + def about_me + respond_to do |format| + format.html {render :text => 'I am html'} + format.xml {render :text => 'I am xml'} + end + end + end class PageCachingTest < ActionController::TestCase @@ -76,7 +85,7 @@ class PageCachingTest < ActionController::TestCase def test_page_caching_resources_saves_to_correct_path_with_extension_even_if_default_route with_routing do |set| - set.draw do |map| + set.draw do match 'posts.:format', :to => 'posts#index', :as => :formatted_posts match '/', :to => 'posts#index', :as => :main end @@ -111,6 +120,13 @@ class PageCachingTest < ActionController::TestCase assert File.exist?("#{FILE_STORE_PATH}/page_caching_test/trailing_slash.html") end + def test_should_obey_http_accept_attribute + @request.env['HTTP_ACCEPT'] = 'text/xml' + get :about_me + assert File.exist?("#{FILE_STORE_PATH}/page_caching_test/about_me.xml") + assert_equal 'I am xml', @response.body + end + def test_should_cache_with_trailing_slash_on_url @controller.class.cache_page 'cached content', '/page_caching_test/trailing_slash/' assert File.exist?("#{FILE_STORE_PATH}/page_caching_test/trailing_slash.html") @@ -140,6 +156,17 @@ class PageCachingTest < ActionController::TestCase assert_page_not_cached :ok end + def test_page_caching_directory_set_as_pathname + begin + ActionController::Base.page_cache_directory = Pathname.new(FILE_STORE_PATH) + get :ok + assert_response :ok + assert_page_cached :ok + ensure + ActionController::Base.page_cache_directory = FILE_STORE_PATH + end + end + private def assert_page_cached(action, message = "#{action} should have been cached") assert page_cached?(action), message @@ -185,6 +212,7 @@ class ActionCachingTestController < CachingController def with_layout @cache_this = MockTime.now.to_f.to_s + @title = nil render :text => @cache_this, :layout => true end @@ -240,7 +268,6 @@ class ActionCachingMockController end def request - mocked_path = @mock_path Object.new.instance_eval(<<-EVAL) def path; '#{@mock_path}' end def format; 'all' end @@ -399,7 +426,6 @@ class ActionCacheTest < ActionController::TestCase get :index assert_response :success - new_cached_time = content_to_cache assert_not_equal cached_time, @response.body end @@ -452,7 +478,7 @@ class ActionCacheTest < ActionController::TestCase def test_xml_version_of_resource_is_treated_as_different_cache with_routing do |set| - set.draw do |map| + set.draw do match ':controller(/:action(.:format))' end @@ -533,6 +559,11 @@ class ActionCacheTest < ActionController::TestCase assert_response 404 end + def test_four_oh_four_renders_content + get :four_oh_four + assert_equal "404'd!", @response.body + end + def test_simple_runtime_error_returns_500_for_multiple_requests get :simple_runtime_error assert_response 500 @@ -637,7 +668,7 @@ class FragmentCachingTest < ActionController::TestCase @store.write('views/another_name', 'another_value') @store.write('views/primalgrasp', 'will not expire ;-)') - @controller.expire_fragment /name/ + @controller.expire_fragment(/name/) assert_nil @store.read('views/name') assert_nil @store.read('views/another_name') @@ -727,23 +758,23 @@ CACHED def test_fragment_caching_in_partials get :html_fragment_cached_with_partial assert_response :success - assert_match /Old fragment caching in a partial/, @response.body - assert_match "Old fragment caching in a partial", @store.read('views/test.host/functional_caching/html_fragment_cached_with_partial') + assert_match(/Old fragment caching in a partial/, @response.body) + assert_match("Old fragment caching in a partial", @store.read('views/test.host/functional_caching/html_fragment_cached_with_partial')) end def test_render_inline_before_fragment_caching get :inline_fragment_cached assert_response :success - assert_match /Some inline content/, @response.body - assert_match /Some cached content/, @response.body - assert_match "Some cached content", @store.read('views/test.host/functional_caching/inline_fragment_cached') + assert_match(/Some inline content/, @response.body) + assert_match(/Some cached content/, @response.body) + assert_match("Some cached content", @store.read('views/test.host/functional_caching/inline_fragment_cached')) end def test_fragment_caching_in_rjs_partials xhr :get, :js_fragment_cached_with_partial assert_response :success - assert_match /Old fragment caching in a partial/, @response.body - assert_match "Old fragment caching in a partial", @store.read('views/test.host/functional_caching/js_fragment_cached_with_partial') + assert_match(/Old fragment caching in a partial/, @response.body) + assert_match("Old fragment caching in a partial", @store.read('views/test.host/functional_caching/js_fragment_cached_with_partial')) end def test_html_formatted_fragment_caching diff --git a/actionpack/test/controller/capture_test.rb b/actionpack/test/controller/capture_test.rb index 47253f22b8..d78acb8ce8 100644 --- a/actionpack/test/controller/capture_test.rb +++ b/actionpack/test/controller/capture_test.rb @@ -6,21 +6,29 @@ class CaptureController < ActionController::Base def self.controller_path; "test"; end def content_for + @title = nil render :layout => "talk_from_action" end def content_for_with_parameter + @title = nil render :layout => "talk_from_action" end def content_for_concatenated + @title = nil render :layout => "talk_from_action" end def non_erb_block_content_for + @title = nil render :layout => "talk_from_action" end + def proper_block_detection + @todo = "some todo" + end + def rescue_action(e) raise end end @@ -62,8 +70,8 @@ class CaptureTest < ActionController::TestCase end def test_proper_block_detection - @todo = "some todo" get :proper_block_detection + assert_equal "some todo", @response.body end private diff --git a/actionpack/test/controller/content_type_test.rb b/actionpack/test/controller/content_type_test.rb index 967107853b..9500c25a32 100644 --- a/actionpack/test/controller/content_type_test.rb +++ b/actionpack/test/controller/content_type_test.rb @@ -29,18 +29,18 @@ class OldContentTypeController < ActionController::Base render :text => "hello world!" end - def render_default_for_rhtml + def render_default_for_erb end - def render_default_for_rxml + def render_default_for_builder end def render_default_for_rjs end - def render_change_for_rxml + def render_change_for_builder response.content_type = Mime::HTML - render :action => "render_default_for_rxml" + render :action => "render_default_for_builder" end def render_default_content_types_for_respond_to @@ -108,23 +108,23 @@ class ContentTypeTest < ActionController::TestCase assert_equal "utf-8", @response.charset, @response.headers.inspect end - def test_nil_default_for_rhtml + def test_nil_default_for_erb OldContentTypeController.default_charset = nil - get :render_default_for_rhtml + get :render_default_for_erb assert_equal Mime::HTML, @response.content_type assert_nil @response.charset, @response.headers.inspect ensure OldContentTypeController.default_charset = "utf-8" end - def test_default_for_rhtml - get :render_default_for_rhtml + def test_default_for_erb + get :render_default_for_erb assert_equal Mime::HTML, @response.content_type assert_equal "utf-8", @response.charset end - def test_default_for_rxml - get :render_default_for_rxml + def test_default_for_builder + get :render_default_for_builder assert_equal Mime::XML, @response.content_type assert_equal "utf-8", @response.charset end @@ -135,8 +135,8 @@ class ContentTypeTest < ActionController::TestCase assert_equal "utf-8", @response.charset end - def test_change_for_rxml - get :render_change_for_rxml + def test_change_for_builder + get :render_change_for_builder assert_equal Mime::HTML, @response.content_type assert_equal "utf-8", @response.charset end diff --git a/actionpack/test/controller/dispatcher_test.rb b/actionpack/test/controller/dispatcher_test.rb deleted file mode 100644 index 7e19bce3b7..0000000000 --- a/actionpack/test/controller/dispatcher_test.rb +++ /dev/null @@ -1,59 +0,0 @@ -require 'abstract_unit' - -# Ensure deprecated dispatcher works -class DeprecatedDispatcherTest < ActiveSupport::TestCase - class DummyApp - def call(env) - [200, {}, 'response'] - end - end - - def setup - ActionDispatch::Callbacks.reset_callbacks(:prepare) - ActionDispatch::Callbacks.reset_callbacks(:call) - end - - def test_assert_deprecated_to_prepare - a = nil - - assert_deprecated do - ActionController::Dispatcher.to_prepare { a = 1 } - end - - assert_nil a - dispatch - assert_equal 1, a - end - - def test_assert_deprecated_before_dispatch - a = nil - - assert_deprecated do - ActionController::Dispatcher.before_dispatch { a = 1 } - end - - assert_nil a - dispatch - assert_equal 1, a - end - - def test_assert_deprecated_after_dispatch - a = nil - - assert_deprecated do - ActionController::Dispatcher.after_dispatch { a = 1 } - end - - assert_nil a - dispatch - assert_equal 1, a - end - - private - - def dispatch(cache_classes = true) - @dispatcher ||= ActionDispatch::Callbacks.new(DummyApp.new, !cache_classes) - @dispatcher.call({'rack.input' => StringIO.new('')}) - end - -end diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb index 14f1bd797a..9e44e8e088 100644 --- a/actionpack/test/controller/filters_test.rb +++ b/actionpack/test/controller/filters_test.rb @@ -78,7 +78,8 @@ class FilterTest < ActionController::TestCase end class RenderingController < ActionController::Base - before_filter :render_something_else + before_filter :before_filter_rendering + after_filter :unreached_after_filter def show @ran_action = true @@ -86,9 +87,59 @@ class FilterTest < ActionController::TestCase end private - def render_something_else + def before_filter_rendering + @ran_filter ||= [] + @ran_filter << "before_filter_rendering" render :inline => "something else" end + + def unreached_after_filter + @ran_filter << "unreached_after_filter_after_render" + end + end + + class RenderingForPrependAfterFilterController < RenderingController + prepend_after_filter :unreached_prepend_after_filter + + private + def unreached_prepend_after_filter + @ran_filter << "unreached_preprend_after_filter_after_render" + end + end + + class BeforeFilterRedirectionController < ActionController::Base + before_filter :before_filter_redirects + after_filter :unreached_after_filter + + def show + @ran_action = true + render :inline => "ran show action" + end + + def target_of_redirection + @ran_target_of_redirection = true + render :inline => "ran target_of_redirection action" + end + + private + def before_filter_redirects + @ran_filter ||= [] + @ran_filter << "before_filter_redirects" + redirect_to(:action => 'target_of_redirection') + end + + def unreached_after_filter + @ran_filter << "unreached_after_filter_after_redirection" + end + end + + class BeforeFilterRedirectionForPrependAfterFilterController < BeforeFilterRedirectionController + prepend_after_filter :unreached_prepend_after_filter_after_redirection + + private + def unreached_prepend_after_filter_after_redirection + @ran_filter << "unreached_prepend_after_filter_after_redirection" + end end class ConditionalFilterController < ActionController::Base @@ -314,6 +365,7 @@ class FilterTest < ActionController::TestCase def initialize @@execution_log = "" + super() end before_filter { |c| c.class.execution_log << " before procfilter " } @@ -447,18 +499,34 @@ class FilterTest < ActionController::TestCase class ::AppSweeper < ActionController::Caching::Sweeper; end class SweeperTestController < ActionController::Base - cache_sweeper :app_sweeper + cache_sweeper :app_sweeper def show render :text => 'hello world' end end + + class ImplicitActionsController < ActionController::Base + before_filter :find_only, :only => :edit + before_filter :find_except, :except => :edit + + private + + def find_only + @only = 'Only' + end + + def find_except + @except = 'Except' + end + end + def test_sweeper_should_not_block_rendering response = test_process(SweeperTestController) assert_equal 'hello world', response.body end def test_before_method_of_sweeper_should_always_return_true - sweeper = ActionController::Caching::Sweeper.send(:new) + sweeper = ActionController::Caching::Sweeper.send(:new) assert sweeper.before(TestController.new) end @@ -611,7 +679,7 @@ class FilterTest < ActionController::TestCase end def test_prepending_and_appending_around_filter - controller = test_process(MixedFilterController) + test_process(MixedFilterController) assert_equal " before aroundfilter before procfilter before appended aroundfilter " + " after appended aroundfilter after procfilter after aroundfilter ", MixedFilterController.execution_log @@ -623,6 +691,32 @@ class FilterTest < ActionController::TestCase assert !assigns["ran_action"] end + def test_before_filter_rendering_breaks_filtering_chain_for_after_filter + test_process(RenderingController) + assert_equal %w( before_filter_rendering ), assigns["ran_filter"] + assert !assigns["ran_action"] + end + + def test_before_filter_redirects_breaks_filtering_chain_for_after_filter + test_process(BeforeFilterRedirectionController) + assert_response :redirect + assert_equal "http://test.host/filter_test/before_filter_redirection/target_of_redirection", redirect_to_url + assert_equal %w( before_filter_redirects ), assigns["ran_filter"] + end + + def test_before_filter_rendering_breaks_filtering_chain_for_preprend_after_filter + test_process(RenderingForPrependAfterFilterController) + assert_equal %w( before_filter_rendering ), assigns["ran_filter"] + assert !assigns["ran_action"] + end + + def test_before_filter_redirects_breaks_filtering_chain_for_preprend_after_filter + test_process(BeforeFilterRedirectionForPrependAfterFilterController) + assert_response :redirect + assert_equal "http://test.host/filter_test/before_filter_redirection_for_prepend_after_filter/target_of_redirection", redirect_to_url + assert_equal %w( before_filter_redirects ), assigns["ran_filter"] + end + def test_filters_with_mixed_specialization_run_in_order assert_nothing_raised do response = test_process(MixedSpecializationController, 'bar') @@ -668,7 +762,7 @@ class FilterTest < ActionController::TestCase assert_equal %w( ensure_login find_user ), assigns["ran_filter"] test_process(ConditionalSkippingController, "login") - assert_nil @controller.instance_variable_get("@ran_after_filter") + assert !@controller.instance_variable_defined?("@ran_after_filter") test_process(ConditionalSkippingController, "change_password") assert_equal %w( clean_up ), @controller.instance_variable_get("@ran_after_filter") end @@ -704,6 +798,18 @@ class FilterTest < ActionController::TestCase assert_equal("I rescued this: #<FilterTest::ErrorToRescue: Something made the bad noise.>", response.body) end + def test_filters_obey_only_and_except_for_implicit_actions + test_process(ImplicitActionsController, 'show') + assert_equal 'Except', assigns(:except) + assert_nil assigns(:only) + assert_equal 'show', response.body + + test_process(ImplicitActionsController, 'edit') + assert_equal 'Only', assigns(:only) + assert_nil assigns(:except) + assert_equal 'edit', response.body + end + private def test_process(controller, action = "show") @controller = controller.is_a?(Class) ? controller.new : controller @@ -756,12 +862,12 @@ class ControllerWithSymbolAsFilter < PostsController def without_exception # Do stuff... - 1 + 1 + wtf = 1 + 1 yield # Do stuff... - 1 + 1 + wtf += 1 end end diff --git a/actionpack/test/controller/flash_test.rb b/actionpack/test/controller/flash_test.rb index 4be09f8c83..3569a2f213 100644 --- a/actionpack/test/controller/flash_test.rb +++ b/actionpack/test/controller/flash_test.rb @@ -209,7 +209,7 @@ class FlashTest < ActionController::TestCase end end -class FlashIntegrationTest < ActionController::IntegrationTest +class FlashIntegrationTest < ActionDispatch::IntegrationTest SessionKey = '_myapp_session' SessionSecret = 'b3c631c314c0bbca50c1b2843150fe33' @@ -255,7 +255,7 @@ class FlashIntegrationTest < ActionController::IntegrationTest def with_test_route_set with_routing do |set| - set.draw do |map| + set.draw do match ':action', :to => FlashIntegrationTest::TestController end diff --git a/actionpack/test/controller/helper_test.rb b/actionpack/test/controller/helper_test.rb index 9b9657929f..9f0670ffdf 100644 --- a/actionpack/test/controller/helper_test.rb +++ b/actionpack/test/controller/helper_test.rb @@ -25,6 +25,32 @@ class AllHelpersController < ActionController::Base helper :all end +module ImpressiveLibrary + extend ActiveSupport::Concern + included do + helper_method :useful_function + end + + def useful_function() end +end + +ActionController::Base.send :include, ImpressiveLibrary + +class JustMeController < ActionController::Base + clear_helpers + + def flash + render :inline => "<h1><%= notice %></h1>" + end + + def lib + render :inline => '<%= useful_function %>' + end +end + +class MeTooController < JustMeController +end + module LocalAbcHelper def a() end def b() end @@ -50,7 +76,7 @@ class HelperTest < ActiveSupport::TestCase # Set default test helper. self.test_helper = LocalAbcHelper end - + def test_deprecated_helper assert_equal expected_helper_methods, missing_methods assert_nothing_raised { @controller_class.helper TestHelper } @@ -70,28 +96,45 @@ class HelperTest < ActiveSupport::TestCase def call_controller(klass, action) request = ActionController::TestRequest.new - klass.action(action).call(request.env) + klass.action(action).call(request.env) end def test_helper_for_nested_controller - assert_equal 'hello: Iz guuut!', + assert_equal 'hello: Iz guuut!', call_controller(Fun::GamesController, "render_hello_world").last.body # request = ActionController::TestRequest.new - # + # # resp = Fun::GamesController.action(:render_hello_world).call(request.env) # assert_equal 'hello: Iz guuut!', resp.last.body end def test_helper_for_acronym_controller assert_equal "test: baz", call_controller(Fun::PdfController, "test").last.body - # + # # request = ActionController::TestRequest.new # response = ActionController::TestResponse.new # request.action = 'test' - # + # # assert_equal 'test: baz', Fun::PdfController.process(request, response).body end + def test_default_helpers_only + assert_equal [JustMeHelper], JustMeController._helpers.ancestors.reject(&:anonymous?) + assert_equal [MeTooHelper, JustMeHelper], MeTooController._helpers.ancestors.reject(&:anonymous?) + end + + def test_base_helper_methods_after_clear_helpers + assert_nothing_raised do + call_controller(JustMeController, "flash") + end + end + + def test_lib_helper_methods_after_clear_helpers + assert_nothing_raised do + call_controller(JustMeController, "lib") + end + end + def test_all_helpers methods = AllHelpersController._helpers.instance_methods.map {|m| m.to_s} @@ -135,17 +178,6 @@ class HelperTest < ActiveSupport::TestCase assert methods.include?('foobar') end - def test_deprecation - assert_deprecated do - ActionController::Base.helpers_dir = "some/foo/bar" - end - assert_deprecated do - assert_equal ["some/foo/bar"], ActionController::Base.helpers_dir - end - ensure - ActionController::Base.helpers_path = File.expand_path('../../fixtures/helpers', __FILE__) - end - private def expected_helper_methods TestHelper.instance_methods.map {|m| m.to_s } @@ -192,7 +224,7 @@ class IsolatedHelpersTest < ActiveSupport::TestCase def call_controller(klass, action) request = ActionController::TestRequest.new - klass.action(action).call(request.env) + klass.action(action).call(request.env) end def setup diff --git a/actionpack/test/controller/http_basic_authentication_test.rb b/actionpack/test/controller/http_basic_authentication_test.rb index 23688ca584..01c650a494 100644 --- a/actionpack/test/controller/http_basic_authentication_test.rb +++ b/actionpack/test/controller/http_basic_authentication_test.rb @@ -13,7 +13,7 @@ class HttpBasicAuthenticationTest < ActionController::TestCase def display render :text => 'Definitely Maybe' end - + def show render :text => 'Only for loooooong credentials' end @@ -33,7 +33,7 @@ class HttpBasicAuthenticationTest < ActionController::TestCase request_http_basic_authentication("SuperSecret") end end - + def authenticate_long_credentials authenticate_or_request_with_http_basic do |username, password| username == '1234567890123456789012345678901234567890' && password == '1234567890123456789012345678901234567890' @@ -56,7 +56,7 @@ class HttpBasicAuthenticationTest < ActionController::TestCase test "successful authentication with #{header.downcase} and long credentials" do @request.env[header] = encode_credentials('1234567890123456789012345678901234567890', '1234567890123456789012345678901234567890') get :show - + assert_response :success assert_equal 'Only for loooooong credentials', @response.body, "Authentication failed for request header #{header} and long credentials" end diff --git a/actionpack/test/controller/http_token_authentication_test.rb b/actionpack/test/controller/http_token_authentication_test.rb index 3dfccae3db..3054c1684c 100644 --- a/actionpack/test/controller/http_token_authentication_test.rb +++ b/actionpack/test/controller/http_token_authentication_test.rb @@ -13,7 +13,7 @@ class HttpTokenAuthenticationTest < ActionController::TestCase def display render :text => 'Definitely Maybe' end - + def show render :text => 'Only for loooooong credentials' end @@ -33,7 +33,7 @@ class HttpTokenAuthenticationTest < ActionController::TestCase request_http_token_authentication("SuperSecret") end end - + def authenticate_long_credentials authenticate_or_request_with_http_token do |token, options| token == '1234567890123456789012345678901234567890' && options[:algorithm] == 'test' @@ -56,7 +56,7 @@ class HttpTokenAuthenticationTest < ActionController::TestCase test "successful authentication with #{header.downcase} and long credentials" do @request.env[header] = encode_credentials('1234567890123456789012345678901234567890', :algorithm => 'test') get :show - + assert_response :success assert_equal 'Only for loooooong credentials', @response.body, "Authentication failed for request header #{header} and long credentials" end diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb index 5ee8e2b6ae..f0d62b0b13 100644 --- a/actionpack/test/controller/integration_test.rb +++ b/actionpack/test/controller/integration_test.rb @@ -8,7 +8,7 @@ class SessionTest < Test::Unit::TestCase } def setup - @session = ActionController::Integration::Session.new(StubApp) + @session = ActionDispatch::Integration::Session.new(StubApp) end def test_https_bang_works_and_sets_truth_by_default @@ -167,7 +167,7 @@ end class IntegrationTestTest < Test::Unit::TestCase def setup - @test = ::ActionController::IntegrationTest.new(:default_test) + @test = ::ActionDispatch::IntegrationTest.new(:app) @test.class.stubs(:fixture_table_names).returns([]) @session = @test.open_session end @@ -202,7 +202,7 @@ end # Tests that integration tests don't call Controller test methods for processing. # Integration tests have their own setup and teardown. -class IntegrationTestUsesCorrectClass < ActionController::IntegrationTest +class IntegrationTestUsesCorrectClass < ActionDispatch::IntegrationTest def self.fixture_table_names [] end @@ -218,7 +218,7 @@ class IntegrationTestUsesCorrectClass < ActionController::IntegrationTest end end -class IntegrationProcessTest < ActionController::IntegrationTest +class IntegrationProcessTest < ActionDispatch::IntegrationTest class IntegrationController < ActionController::Base def get respond_to do |format| @@ -427,7 +427,7 @@ class IntegrationProcessTest < ActionController::IntegrationTest include set.url_helpers end - set.draw do |map| + set.draw do match ':action', :to => controller get 'get/:action', :to => controller end @@ -439,7 +439,7 @@ class IntegrationProcessTest < ActionController::IntegrationTest end end -class MetalIntegrationTest < ActionController::IntegrationTest +class MetalIntegrationTest < ActionDispatch::IntegrationTest include SharedTestRoutes.url_helpers class Poller @@ -476,7 +476,7 @@ class MetalIntegrationTest < ActionController::IntegrationTest end end -class ApplicationIntegrationTest < ActionController::IntegrationTest +class ApplicationIntegrationTest < ActionDispatch::IntegrationTest class TestController < ActionController::Base def index render :text => "index" diff --git a/actionpack/test/controller/layout_test.rb b/actionpack/test/controller/layout_test.rb index 165c61ffad..cafe2b9320 100644 --- a/actionpack/test/controller/layout_test.rb +++ b/actionpack/test/controller/layout_test.rb @@ -46,13 +46,13 @@ class LayoutAutoDiscoveryTest < ActionController::TestCase def test_application_layout_is_default_when_no_controller_match @controller = ProductController.new get :hello - assert_equal 'layout_test.rhtml hello.rhtml', @response.body + assert_equal 'layout_test.erb hello.erb', @response.body end def test_controller_name_layout_name_match @controller = ItemController.new get :hello - assert_equal 'item.rhtml hello.rhtml', @response.body + assert_equal 'item.erb hello.erb', @response.body end def test_third_party_template_library_auto_discovers_layout @@ -65,13 +65,13 @@ class LayoutAutoDiscoveryTest < ActionController::TestCase def test_namespaced_controllers_auto_detect_layouts1 @controller = ControllerNameSpace::NestedController.new get :hello - assert_equal 'controller_name_space/nested.rhtml hello.rhtml', @response.body + assert_equal 'controller_name_space/nested.erb hello.erb', @response.body end def test_namespaced_controllers_auto_detect_layouts2 @controller = MultipleExtensions.new get :hello - assert_equal 'multiple_extensions.html.erb hello.rhtml', @response.body.strip + assert_equal 'multiple_extensions.html.erb hello.erb', @response.body.strip end end @@ -79,7 +79,7 @@ class DefaultLayoutController < LayoutTest end class AbsolutePathLayoutController < LayoutTest - layout File.expand_path(File.expand_path(__FILE__) + '/../../fixtures/layout_tests/layouts/layout_test.rhtml') + layout File.expand_path(File.expand_path(__FILE__) + '/../../fixtures/layout_tests/layouts/layout_test.erb') end class HasOwnLayoutController < LayoutTest @@ -115,7 +115,7 @@ end class LayoutSetInResponseTest < ActionController::TestCase include ActionView::Template::Handlers - + def test_layout_set_when_using_default_layout @controller = DefaultLayoutController.new get :hello @@ -127,7 +127,7 @@ class LayoutSetInResponseTest < ActionController::TestCase get :hello assert_template :layout => "layouts/item" end - + def test_layout_only_exception_when_included @controller = OnlyLayoutController.new get :hello @@ -137,7 +137,7 @@ class LayoutSetInResponseTest < ActionController::TestCase def test_layout_only_exception_when_excepted @controller = OnlyLayoutController.new get :goodbye - assert !@response.body.include?("item.rhtml"), "#{@response.body.inspect} included 'item.rhtml'" + assert !@response.body.include?("item.erb"), "#{@response.body.inspect} included 'item.erb'" end def test_layout_except_exception_when_included @@ -149,7 +149,7 @@ class LayoutSetInResponseTest < ActionController::TestCase def test_layout_except_exception_when_excepted @controller = ExceptLayoutController.new get :goodbye - assert !@response.body.include?("item.rhtml"), "#{@response.body.inspect} included 'item.rhtml'" + assert !@response.body.include?("item.erb"), "#{@response.body.inspect} included 'item.erb'" end def test_layout_set_when_using_render @@ -173,7 +173,7 @@ class LayoutSetInResponseTest < ActionController::TestCase def test_absolute_pathed_layout @controller = AbsolutePathLayoutController.new get :hello - assert_equal "layout_test.rhtml hello.rhtml", @response.body.strip + assert_equal "layout_test.erb hello.erb", @response.body.strip end end @@ -184,7 +184,7 @@ class RenderWithTemplateOptionController < LayoutTest end class SetsNonExistentLayoutFile < LayoutTest - layout "nofile.rhtml" + layout "nofile.erb" end class LayoutExceptionRaised < ActionController::TestCase @@ -208,7 +208,7 @@ class LayoutStatusIsRenderedTest < ActionController::TestCase end end -unless Config::CONFIG['host_os'] =~ /mswin|mingw/ +unless RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ class LayoutSymlinkedTest < LayoutTest layout "symlinked/symlinked_layout" end diff --git a/actionpack/test/controller/log_subscriber_test.rb b/actionpack/test/controller/log_subscriber_test.rb index 0a18741f0c..ddfa3df552 100644 --- a/actionpack/test/controller/log_subscriber_test.rb +++ b/actionpack/test/controller/log_subscriber_test.rb @@ -16,10 +16,6 @@ module Another send_data "cool data", :filename => "file.txt" end - def xfile_sender - send_file File.expand_path("company.rb", FIXTURE_LOAD_PATH), :x_sendfile => true - end - def file_sender send_file File.expand_path("company.rb", FIXTURE_LOAD_PATH) end @@ -28,10 +24,19 @@ module Another render :inline => "<%= cache('foo'){ 'bar' } %>" end + def with_fragment_cache_and_percent_in_key + render :inline => "<%= cache('foo%bar'){ 'Contains % sign in key' } %>" + end + def with_page_cache cache_page("Super soaker", "/index.html") render :nothing => true end + + def with_exception + raise Exception + end + end end @@ -72,8 +77,8 @@ class ACLogSubscriberTest < ActionController::TestCase get :show wait assert_equal 2, logs.size - assert_match /Completed/, logs.last - assert_match /200 OK/, logs.last + assert_match(/Completed/, logs.last) + assert_match(/200 OK/, logs.last) end def test_process_action_without_parameters @@ -93,7 +98,7 @@ class ACLogSubscriberTest < ActionController::TestCase def test_process_action_with_view_runtime get :show wait - assert_match /\(Views: [\d\.]+ms\)/, logs[1] + assert_match(/\(Views: [\d.]+ms\)/, logs[1]) end def test_process_action_with_filter_parameters @@ -103,9 +108,9 @@ class ACLogSubscriberTest < ActionController::TestCase wait params = logs[1] - assert_match /"amount"=>"\[FILTERED\]"/, params - assert_match /"lifo"=>"\[FILTERED\]"/, params - assert_match /"step"=>"1"/, params + assert_match(/"amount"=>"\[FILTERED\]"/, params) + assert_match(/"lifo"=>"\[FILTERED\]"/, params) + assert_match(/"step"=>"1"/, params) end def test_redirect_to @@ -121,7 +126,7 @@ class ACLogSubscriberTest < ActionController::TestCase wait assert_equal 3, logs.size - assert_match /Sent data file\.txt/, logs[1] + assert_match(/Sent data file\.txt/, logs[1]) end def test_send_file @@ -129,27 +134,30 @@ class ACLogSubscriberTest < ActionController::TestCase wait assert_equal 3, logs.size - assert_match /Sent file/, logs[1] - assert_match /test\/fixtures\/company\.rb/, logs[1] + assert_match(/Sent file/, logs[1]) + assert_match(/test\/fixtures\/company\.rb/, logs[1]) end - def test_send_xfile - assert_deprecated { get :xfile_sender } + def test_with_fragment_cache + @controller.config.perform_caching = true + get :with_fragment_cache wait - assert_equal 3, logs.size - assert_match /Sent file/, logs[1] - assert_match /test\/fixtures\/company\.rb/, logs[1] + assert_equal 4, logs.size + assert_match(/Read fragment views\/foo/, logs[1]) + assert_match(/Write fragment views\/foo/, logs[2]) + ensure + @controller.config.perform_caching = true end - def test_with_fragment_cache + def test_with_fragment_cache_and_percent_in_key @controller.config.perform_caching = true - get :with_fragment_cache + get :with_fragment_cache_and_percent_in_key wait assert_equal 4, logs.size - assert_match /Exist fragment\? views\/foo/, logs[1] - assert_match /Write fragment views\/foo/, logs[2] + assert_match(/Read fragment views\/foo/, logs[1]) + assert_match(/Write fragment views\/foo/, logs[2]) ensure @controller.config.perform_caching = true end @@ -160,12 +168,22 @@ class ACLogSubscriberTest < ActionController::TestCase wait assert_equal 3, logs.size - assert_match /Write page/, logs[1] - assert_match /\/index\.html/, logs[1] + assert_match(/Write page/, logs[1]) + assert_match(/\/index\.html/, logs[1]) ensure @controller.config.perform_caching = true end + def test_process_action_with_exception_includes_http_status_code + begin + get :with_exception + wait + rescue Exception + end + assert_equal 2, logs.size + assert_match(/Completed 500/, logs.last) + end + def logs @logs ||= @logger.logged(:info) end diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb index b5ce391b61..5debf96232 100644 --- a/actionpack/test/controller/mime_responds_test.rb +++ b/actionpack/test/controller/mime_responds_test.rb @@ -2,6 +2,14 @@ require 'abstract_unit' require 'controller/fake_models' require 'active_support/core_ext/hash/conversions' +class StarStarMimeController < ActionController::Base + layout nil + + def index + render + end +end + class RespondToController < ActionController::Base layout :set_layout @@ -36,7 +44,7 @@ class RespondToController < ActionController::Base type.all { render :text => "Nothing" } end end - + def json_xml_or_html respond_to do |type| type.json { render :text => 'JSON' } @@ -44,7 +52,7 @@ class RespondToController < ActionController::Base type.html { render :text => 'HTML' } end end - + def forced_xml request.format = :xml @@ -89,7 +97,6 @@ class RespondToController < ActionController::Base end end - Mime::Type.register("text/x-mobile", :mobile) def custom_constant_handling respond_to do |type| @@ -126,7 +133,6 @@ class RespondToController < ActionController::Base end end - Mime::Type.register_alias("text/html", :iphone) def iphone_with_html_response_type request.format = :iphone if request.env["HTTP_ACCEPT"] == "text/iphone" @@ -160,16 +166,43 @@ class RespondToController < ActionController::Base end end +class StarStarMimeControllerTest < ActionController::TestCase + tests StarStarMimeController + + def test_javascript_with_format + @request.accept = "text/javascript" + get :index, :format => 'js' + assert_match "function addition(a,b){ return a+b; }", @response.body + end + + def test_javascript_with_no_format + @request.accept = "text/javascript" + get :index + assert_match "function addition(a,b){ return a+b; }", @response.body + end + + def test_javascript_with_no_format_only_star_star + @request.accept = "*/*" + get :index + assert_match "function addition(a,b){ return a+b; }", @response.body + end + +end + class RespondToControllerTest < ActionController::TestCase tests RespondToController def setup super @request.host = "www.example.com" + Mime::Type.register_alias("text/html", :iphone) + Mime::Type.register("text/x-mobile", :mobile) end def teardown super + Mime::Type.unregister(:iphone) + Mime::Type.unregister(:mobile) end def test_html @@ -216,6 +249,16 @@ class RespondToControllerTest < ActionController::TestCase assert_response 406 end + def test_json_or_yaml_with_leading_star_star + @request.accept = "*/*, application/json" + get :json_xml_or_html + assert_equal 'HTML', @response.body + + @request.accept = "*/* , application/json" + get :json_xml_or_html + assert_equal 'HTML', @response.body + end + def test_json_or_yaml xhr :get, :json_or_yaml assert_equal 'JSON', @response.body @@ -373,17 +416,17 @@ class RespondToControllerTest < ActionController::TestCase get :handle_any_any assert_equal 'Whatever you ask for, I got it', @response.body end - + def test_browser_check_with_any_any @request.accept = "application/json, application/xml" get :json_xml_or_html assert_equal 'JSON', @response.body - + @request.accept = "application/json, application/xml, */*" get :json_xml_or_html assert_equal 'HTML', @response.body end - + def test_rjs_type_skips_layout @request.accept = "text/javascript" @@ -487,6 +530,10 @@ class RespondWithController < ActionController::Base respond_with(resource) end + def using_hash_resource + respond_with({:result => resource}) + end + def using_resource_with_block respond_with(resource) do |format| format.csv { render :text => "CSV" } @@ -518,7 +565,7 @@ class RespondWithController < ActionController::Base def using_resource_with_action respond_with(resource, :action => :foo) do |format| - format.html { raise ActionView::MissingTemplate.new([], "foo/bar", {}, false) } + format.html { raise ActionView::MissingTemplate.new([], "bar", ["foo"], {}, false) } end end @@ -552,6 +599,17 @@ class InheritedRespondWithController < RespondWithController end end +class RenderJsonRespondWithController < RespondWithController + clear_respond_to + respond_to :json + + def index + respond_with(resource) do |format| + format.json { render :json => RenderJsonTestException.new('boom') } + end + end +end + class EmptyRespondWithController < ActionController::Base def index respond_with(Customer.new("david", 13)) @@ -564,10 +622,14 @@ class RespondWithControllerTest < ActionController::TestCase def setup super @request.host = "www.example.com" + Mime::Type.register_alias('text/html', :iphone) + Mime::Type.register('text/x-mobile', :mobile) end def teardown super + Mime::Type.unregister(:iphone) + Mime::Type.unregister(:mobile) end def test_using_resource @@ -587,6 +649,18 @@ class RespondWithControllerTest < ActionController::TestCase end end + def test_using_hash_resource + @request.accept = "application/xml" + get :using_hash_resource + assert_equal "application/xml", @response.content_type + assert_equal "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<hash>\n <name>david</name>\n</hash>\n", @response.body + + @request.accept = "application/json" + get :using_hash_resource + assert_equal "application/json", @response.content_type + assert_equal %Q[{"result":{"name":"david","id":13}}], @response.body + end + def test_using_resource_with_block @request.accept = "*/*" get :using_resource_with_block @@ -709,6 +783,15 @@ class RespondWithControllerTest < ActionController::TestCase assert_equal " ", @response.body end + def test_using_resource_for_put_with_json_yields_ok_on_success + Customer.any_instance.stubs(:to_json).returns('{"name": "David"}') + @request.accept = "application/json" + put :using_resource + assert_equal "application/json", @response.content_type + assert_equal 200, @response.status + assert_equal "{}", @response.body + end + def test_using_resource_for_put_with_xml_yields_unprocessable_entity_on_failure @request.accept = "application/xml" errors = { :name => :invalid } @@ -739,6 +822,16 @@ class RespondWithControllerTest < ActionController::TestCase assert_equal " ", @response.body end + def test_using_resource_for_delete_with_json_yields_ok_on_success + Customer.any_instance.stubs(:to_json).returns('{"name": "David"}') + Customer.any_instance.stubs(:destroyed?).returns(true) + @request.accept = "application/json" + delete :using_resource + assert_equal "application/json", @response.content_type + assert_equal 200, @response.status + assert_equal "{}", @response.body + end + def test_using_resource_for_delete_with_html_redirects_on_failure with_test_route_set do errors = { :name => :invalid } @@ -784,8 +877,8 @@ class RespondWithControllerTest < ActionController::TestCase get :using_resource_with_collection assert_equal "application/xml", @response.content_type assert_equal 200, @response.status - assert_match /<name>david<\/name>/, @response.body - assert_match /<name>jamis<\/name>/, @response.body + assert_match(/<name>david<\/name>/, @response.body) + assert_match(/<name>jamis<\/name>/, @response.body) end def test_using_resource_with_action @@ -834,6 +927,14 @@ class RespondWithControllerTest < ActionController::TestCase assert_equal "JSON", @response.body end + def test_render_json_object_responds_to_str_still_produce_json + @controller = RenderJsonRespondWithController.new + @request.accept = "application/json" + get :index, :format => :json + assert_match(/"message":"boom"/, @response.body) + assert_match(/"error":"RenderJsonTestException"/, @response.body) + end + def test_no_double_render_is_raised @request.accept = "text/html" assert_raise ActionView::MissingTemplate do @@ -876,7 +977,7 @@ class RespondWithControllerTest < ActionController::TestCase private def with_test_route_set with_routing do |set| - set.draw do |map| + set.draw do resources :customers resources :quiz_stores do resources :customers @@ -917,6 +1018,12 @@ class MimeControllerLayoutsTest < ActionController::TestCase def setup super @request.host = "www.example.com" + Mime::Type.register_alias("text/html", :iphone) + end + + def teardown + super + Mime::Type.unregister(:iphone) end def test_missing_layout_renders_properly diff --git a/actionpack/test/controller/new_base/bare_metal_test.rb b/actionpack/test/controller/new_base/bare_metal_test.rb index 8a06e8d2a0..3ca29f1bcf 100644 --- a/actionpack/test/controller/new_base/bare_metal_test.rb +++ b/actionpack/test/controller/new_base/bare_metal_test.rb @@ -24,4 +24,26 @@ module BareMetalTest assert_equal "Hello world", string end end + + class HeadController < ActionController::Metal + include ActionController::Head + + def index + head :not_found + end + end + + class HeadTest < ActiveSupport::TestCase + test "head works on its own" do + status = HeadController.action(:index).call(Rack::MockRequest.env_for("/")).first + assert_equal 404, status + end + end + + class BareControllerTest < ActionController::TestCase + test "GET index" do + get :index + assert_equal "Hello world", @response.body + end + end end diff --git a/actionpack/test/controller/new_base/content_negotiation_test.rb b/actionpack/test/controller/new_base/content_negotiation_test.rb index b98a22dfcc..5fd5946619 100644 --- a/actionpack/test/controller/new_base/content_negotiation_test.rb +++ b/actionpack/test/controller/new_base/content_negotiation_test.rb @@ -7,6 +7,10 @@ module ContentNegotiation self.view_paths = [ActionView::FixtureResolver.new( "content_negotiation/basic/hello.html.erb" => "Hello world <%= request.formats.first.to_s %>!" )] + + def all + render :text => self.formats.inspect + end end class TestContentNegotiation < Rack::TestCase @@ -14,5 +18,10 @@ module ContentNegotiation get "/content_negotiation/basic/hello", {}, "HTTP_ACCEPT" => "*/*" assert_body "Hello world */*!" end + + test "Not all mimes are converted to symbol" do + get "/content_negotiation/basic/all", {}, "HTTP_ACCEPT" => "text/plain, mime/another" + assert_body '[:text, "mime/another"]' + end end end diff --git a/actionpack/test/controller/new_base/content_type_test.rb b/actionpack/test/controller/new_base/content_type_test.rb index 33c2e442f0..8ba30944f5 100644 --- a/actionpack/test/controller/new_base/content_type_test.rb +++ b/actionpack/test/controller/new_base/content_type_test.rb @@ -42,10 +42,16 @@ module ContentType class ExplicitContentTypeTest < Rack::TestCase test "default response is HTML and UTF8" do - get "/content_type/base" + with_routing do |set| + set.draw do + match ':controller', :action => 'index' + end - assert_body "Hello world!" - assert_header "Content-Type", "text/html; charset=utf-8" + get "/content_type/base" + + assert_body "Hello world!" + assert_header "Content-Type", "text/html; charset=utf-8" + end end test "setting the content type of the response directly on the response object" do diff --git a/actionpack/test/controller/new_base/etag_test.rb b/actionpack/test/controller/new_base/etag_test.rb deleted file mode 100644 index 51bfb2278a..0000000000 --- a/actionpack/test/controller/new_base/etag_test.rb +++ /dev/null @@ -1,46 +0,0 @@ -require 'abstract_unit' - -module Etags - class BasicController < ActionController::Base - self.view_paths = [ActionView::FixtureResolver.new( - "etags/basic/base.html.erb" => "Hello from without_layout.html.erb", - "layouts/etags.html.erb" => "teh <%= yield %> tagz" - )] - - def without_layout - render :action => "base" - end - - def with_layout - render :action => "base", :layout => "etags" - end - end - - class EtagTest < Rack::TestCase - describe "Rendering without any special etag options returns an etag that is an MD5 hash of its text" - - test "an action without a layout" do - get "/etags/basic/without_layout" - - body = "Hello from without_layout.html.erb" - assert_body body - assert_header "Etag", etag_for(body) - assert_status 200 - end - - test "an action with a layout" do - get "/etags/basic/with_layout" - - body = "teh Hello from without_layout.html.erb tagz" - assert_body body - assert_header "Etag", etag_for(body) - assert_status 200 - end - - private - - def etag_for(text) - %("#{Digest::MD5.hexdigest(text)}") - end - end -end diff --git a/actionpack/test/controller/new_base/middleware_test.rb b/actionpack/test/controller/new_base/middleware_test.rb index 26a66c91a6..ccef060863 100644 --- a/actionpack/test/controller/new_base/middleware_test.rb +++ b/actionpack/test/controller/new_base/middleware_test.rb @@ -25,8 +25,25 @@ module MiddlewareTest result end end + + class BlockMiddleware + attr_accessor :configurable_message + def initialize(app, &block) + @app = app + yield(self) if block_given? + end + + def call(env) + result = @app.call(env) + result[1]["Configurable-Message"] = configurable_message + result + end + end class MyController < ActionController::Metal + use BlockMiddleware do |config| + config.configurable_message = "Configured by block." + end use MyMiddleware middleware.insert_before MyMiddleware, ExclaimerMiddleware @@ -67,6 +84,11 @@ module MiddlewareTest assert_equal "First!", result[1]["Middleware-Order"] end + test "middleware stack accepts block arguments" do + result = @app.call(env_for("/")) + assert_equal "Configured by block.", result[1]["Configurable-Message"] + end + test "middleware stack accepts only and except as options" do result = ActionsController.action(:show).call(env_for("/")) assert_equal "First!", result[1]["Middleware-Order"] diff --git a/actionpack/test/controller/new_base/render_action_test.rb b/actionpack/test/controller/new_base/render_action_test.rb index d92e9c4bf2..aa44e0b282 100644 --- a/actionpack/test/controller/new_base/render_action_test.rb +++ b/actionpack/test/controller/new_base/render_action_test.rb @@ -83,6 +83,9 @@ module RenderAction end class RenderLayoutTest < Rack::TestCase + def setup + end + describe "Both <controller_path>.html.erb and application.html.erb are missing" test "rendering with layout => true" do diff --git a/actionpack/test/controller/new_base/render_implicit_action_test.rb b/actionpack/test/controller/new_base/render_implicit_action_test.rb index 90cc7933ff..9f69d20329 100644 --- a/actionpack/test/controller/new_base/render_implicit_action_test.rb +++ b/actionpack/test/controller/new_base/render_implicit_action_test.rb @@ -6,10 +6,10 @@ module RenderImplicitAction "render_implicit_action/simple/hello_world.html.erb" => "Hello world!", "render_implicit_action/simple/hyphen-ated.html.erb" => "Hello hyphen-ated!" )] - + def hello_world() end end - + class RenderImplicitActionTest < Rack::TestCase test "render a simple action with new explicit call to render" do get "/render_implicit_action/simple/hello_world" diff --git a/actionpack/test/controller/new_base/render_layout_test.rb b/actionpack/test/controller/new_base/render_layout_test.rb index 372fb66b88..bb2a953536 100644 --- a/actionpack/test/controller/new_base/render_layout_test.rb +++ b/actionpack/test/controller/new_base/render_layout_test.rb @@ -71,7 +71,7 @@ module ControllerLayouts self.view_paths = [ActionView::FixtureResolver.new( "layouts/application.html.erb" => "<html><%= yield %></html>", "controller_layouts/mismatch_format/index.js.rjs" => "page[:test].ext", - "controller_layouts/mismatch_format/implicit.rjs" => "page[:test].ext" + "controller_layouts/mismatch_format/implicit.rjs" => "page[:test].ext" )] def explicit diff --git a/actionpack/test/controller/new_base/render_once_test.rb b/actionpack/test/controller/new_base/render_once_test.rb new file mode 100644 index 0000000000..175abf8a7e --- /dev/null +++ b/actionpack/test/controller/new_base/render_once_test.rb @@ -0,0 +1,86 @@ +require 'abstract_unit' + +module RenderTemplate + class RenderOnceController < ActionController::Base + layout false + + RESOLVER = ActionView::FixtureResolver.new( + "test/a.html.erb" => "a", + "test/b.html.erb" => "<>", + "test/c.html.erb" => "c", + "test/one.html.erb" => "<%= render :once => 'result' %>", + "test/two.html.erb" => "<%= render :once => 'result' %>", + "test/three.html.erb" => "<%= render :once => 'result' %>", + "test/result.html.erb" => "YES!", + "other/result.html.erb" => "NO!", + "layouts/test.html.erb" => "l<%= yield %>l" + ) + + self.view_paths = [RESOLVER] + + def _prefixes + %w(test) + end + + def multiple + render :once => %w(a b c) + end + + def once + render :once => %w(one two three) + end + + def duplicate + render :once => %w(a a a) + end + + def with_layout + render :once => %w(a b c), :layout => "test" + end + + def with_prefix + render :once => "result", :prefixes => %w(other) + end + + def with_nil_prefix + render :once => "test/result", :prefixes => [] + end + end + + module Tests + def test_mutliple_arguments_get_all_rendered + get :multiple + assert_response "a\n<>\nc" + end + + def test_referenced_templates_get_rendered_once + get :once + assert_response "YES!\n\n" + end + + def test_duplicated_templates_get_rendered_once + get :duplicate + assert_response "a" + end + + def test_layout_wraps_all_rendered_templates + get :with_layout + assert_response "la\n<>\ncl" + end + + def test_with_prefix_option + get :with_prefix + assert_response "NO!" + end + + def test_with_nil_prefix_option + get :with_nil_prefix + assert_response "YES!" + end + end + + class TestRenderOnce < Rack::TestCase + testing RenderTemplate::RenderOnceController + include Tests + end +end diff --git a/actionpack/test/controller/new_base/render_partial_test.rb b/actionpack/test/controller/new_base/render_partial_test.rb index 1a1b36a65e..83b0d039ad 100644 --- a/actionpack/test/controller/new_base/render_partial_test.rb +++ b/actionpack/test/controller/new_base/render_partial_test.rb @@ -1,27 +1,63 @@ require 'abstract_unit' module RenderPartial - + class BasicController < ActionController::Base - + self.view_paths = [ActionView::FixtureResolver.new( - "render_partial/basic/_basic.html.erb" => "BasicPartial!", - "render_partial/basic/basic.html.erb" => "<%= @test_unchanged = 'goodbye' %><%= render :partial => 'basic' %><%= @test_unchanged %>" + "render_partial/basic/_basic.html.erb" => "BasicPartial!", + "render_partial/basic/basic.html.erb" => "<%= @test_unchanged = 'goodbye' %><%= render :partial => 'basic' %><%= @test_unchanged %>", + "render_partial/basic/with_json.html.erb" => "<%= render 'with_json.json' %>", + "render_partial/basic/_with_json.json.erb" => "<%= render 'final' %>", + "render_partial/basic/_final.json.erb" => "{ final: json }", + "render_partial/basic/overriden.html.erb" => "<%= @test_unchanged = 'goodbye' %><%= render :partial => 'overriden' %><%= @test_unchanged %>", + "render_partial/basic/_overriden.html.erb" => "ParentPartial!", + "render_partial/child/_overriden.html.erb" => "OverridenPartial!" )] - + + def html_with_json_inside_json + render :action => "with_json" + end + def changing @test_unchanged = 'hello' render :action => "basic" - end + end + + def overriden + @test_unchanged = 'hello' + end end + class ChildController < BasicController; end + class TestPartial < Rack::TestCase testing BasicController - + test "rendering a partial in ActionView doesn't pull the ivars again from the controller" do get :changing assert_response("goodbyeBasicPartial!goodbye") end + + test "rendering a template with renders another partial with other format that renders other partial in the same format" do + get :html_with_json_inside_json + assert_content_type "text/html; charset=utf-8" + assert_response "{ final: json }" + end end - + + class TestInheritedPartial < Rack::TestCase + testing ChildController + + test "partial from parent controller gets picked if missing in child one" do + get :changing + assert_response("goodbyeBasicPartial!goodbye") + end + + test "partial from child controller gets picked" do + get :overriden + assert_response("goodbyeOverridenPartial!goodbye") + end + end + end diff --git a/actionpack/test/controller/new_base/render_template_test.rb b/actionpack/test/controller/new_base/render_template_test.rb index 70cebbfd89..584f2d772c 100644 --- a/actionpack/test/controller/new_base/render_template_test.rb +++ b/actionpack/test/controller/new_base/render_template_test.rb @@ -4,17 +4,26 @@ module RenderTemplate class WithoutLayoutController < ActionController::Base self.view_paths = [ActionView::FixtureResolver.new( - "test/basic.html.erb" => "Hello from basic.html.erb", - "shared.html.erb" => "Elastica", - "locals.html.erb" => "The secret is <%= secret %>", - "xml_template.xml.builder" => "xml.html do\n xml.p 'Hello'\nend", - "with_raw.html.erb" => "Hello <%=raw '<strong>this is raw</strong>' %>" + "test/basic.html.erb" => "Hello from basic.html.erb", + "shared.html.erb" => "Elastica", + "locals.html.erb" => "The secret is <%= secret %>", + "xml_template.xml.builder" => "xml.html do\n xml.p 'Hello'\nend", + "with_raw.html.erb" => "Hello <%=raw '<strong>this is raw</strong>' %>", + "with_implicit_raw.html.erb" => "Hello <%== '<strong>this is also raw</strong>' %>", + "test/with_json.html.erb" => "<%= render :template => 'test/with_json.json' %>", + "test/with_json.json.erb" => "<%= render :template => 'test/final' %>", + "test/final.json.erb" => "{ final: json }", + "test/with_error.html.erb" => "<%= idontexist %>" )] def index render :template => "test/basic" end + def html_with_json_inside_json + render :template => "test/with_json" + end + def index_without_key render "test/basic" end @@ -42,6 +51,14 @@ module RenderTemplate def with_raw render :template => "with_raw" end + + def with_implicit_raw + render :template => "with_implicit_raw" + end + + def with_error + render :template => "test/with_error" + end end class TestWithoutLayout < Rack::TestCase @@ -87,6 +104,23 @@ module RenderTemplate assert_body "Hello <strong>this is raw</strong>" assert_status 200 + + get :with_implicit_raw + + assert_body "Hello <strong>this is also raw</strong>" + assert_status 200 + end + + test "rendering a template with renders another template with other format that renders other template in the same format" do + get :html_with_json_inside_json + assert_content_type "text/html; charset=utf-8" + assert_response "{ final: json }" + end + + test "rendering a template with error properly exceprts the code" do + get :with_error + assert_status 500 + assert_match "undefined local variable or method `idontexist'", response.body end end @@ -123,10 +157,14 @@ module RenderTemplate describe "Rendering with :template using implicit or explicit layout" test "rendering with implicit layout" do - get "/render_template/with_layout" + with_routing do |set| + set.draw { match ':controller', :action => :index } - assert_body "Hello from basic.html.erb, I'm here!" - assert_status 200 + get "/render_template/with_layout" + + assert_body "Hello from basic.html.erb, I'm here!" + assert_status 200 + end end test "rendering with layout => :true" do diff --git a/actionpack/test/controller/new_base/render_test.rb b/actionpack/test/controller/new_base/render_test.rb index d985d9f9ad..d6062bfa8c 100644 --- a/actionpack/test/controller/new_base/render_test.rb +++ b/actionpack/test/controller/new_base/render_test.rb @@ -6,7 +6,11 @@ module Render "render/blank_render/index.html.erb" => "Hello world!", "render/blank_render/access_request.html.erb" => "The request: <%= request.method.to_s.upcase %>", "render/blank_render/access_action_name.html.erb" => "Action Name: <%= action_name %>", - "render/blank_render/access_controller_name.html.erb" => "Controller Name: <%= controller_name %>" + "render/blank_render/access_controller_name.html.erb" => "Controller Name: <%= controller_name %>", + "render/blank_render/overriden_with_own_view_paths_appended.html.erb" => "parent content", + "render/blank_render/overriden_with_own_view_paths_prepended.html.erb" => "parent content", + "render/blank_render/overriden.html.erb" => "parent content", + "render/child_render/overriden.html.erb" => "child content" )] def index @@ -21,6 +25,15 @@ module Render render :action => "access_action_name" end + def overriden_with_own_view_paths_appended + end + + def overriden_with_own_view_paths_prepended + end + + def overriden + end + private def secretz @@ -35,17 +48,34 @@ module Render end end + class ChildRenderController < BlankRenderController + append_view_path ActionView::FixtureResolver.new("render/child_render/overriden_with_own_view_paths_appended.html.erb" => "child content") + prepend_view_path ActionView::FixtureResolver.new("render/child_render/overriden_with_own_view_paths_prepended.html.erb" => "child content") + end + class RenderTest < Rack::TestCase test "render with blank" do - get "/render/blank_render" + with_routing do |set| + set.draw do + match ":controller", :action => 'index' + end - assert_body "Hello world!" - assert_status 200 + get "/render/blank_render" + + assert_body "Hello world!" + assert_status 200 + end end test "rendering more than once raises an exception" do - assert_raises(AbstractController::DoubleRenderError) do - get "/render/double_render", {}, "action_dispatch.show_exceptions" => false + with_routing do |set| + set.draw do + match ":controller", :action => 'index' + end + + assert_raises(AbstractController::DoubleRenderError) do + get "/render/double_render", {}, "action_dispatch.show_exceptions" => false + end end end end @@ -65,7 +95,7 @@ module Render end end end - + class TestVariousObjectsAvailableInView < Rack::TestCase test "The request object is accessible in the view" do get "/render/blank_render/access_request" @@ -82,4 +112,26 @@ module Render assert_body "Controller Name: blank_render" end end + + class TestViewInheritance < Rack::TestCase + test "Template from child controller gets picked over parent one" do + get "/render/child_render/overriden" + assert_body "child content" + end + + test "Template from child controller with custom view_paths prepended gets picked over parent one" do + get "/render/child_render/overriden_with_own_view_paths_prepended" + assert_body "child content" + end + + test "Template from child controller with custom view_paths appended gets picked over parent one" do + get "/render/child_render/overriden_with_own_view_paths_appended" + assert_body "child content" + end + + test "Template from parent controller gets picked if missing in child controller" do + get "/render/child_render/index" + assert_body "Hello world!" + end + end end diff --git a/actionpack/test/controller/new_base/render_text_test.rb b/actionpack/test/controller/new_base/render_text_test.rb index 0e6f51c998..06d500cca7 100644 --- a/actionpack/test/controller/new_base/render_text_test.rb +++ b/actionpack/test/controller/new_base/render_text_test.rb @@ -3,7 +3,7 @@ require 'abstract_unit' module RenderText class SimpleController < ActionController::Base self.view_paths = [ActionView::FixtureResolver.new] - + def index render :text => "hello david" end @@ -14,24 +14,24 @@ module RenderText "layouts/application.html.erb" => "<%= yield %>, I'm here!", "layouts/greetings.html.erb" => "<%= yield %>, I wish thee well.", "layouts/ivar.html.erb" => "<%= yield %>, <%= @ivar %>" - )] - + )] + def index render :text => "hello david" end - + def custom_code render :text => "hello world", :status => 404 end - + def with_custom_code_as_string render :text => "hello world", :status => "404 Not Found" end - + def with_nil render :text => nil end - + def with_nil_and_status render :text => nil, :status => 403 end @@ -39,23 +39,23 @@ module RenderText def with_false render :text => false end - + def with_layout_true render :text => "hello world", :layout => true end - + def with_layout_false render :text => "hello world", :layout => false end - + def with_layout_nil render :text => "hello world", :layout => nil end - + def with_custom_layout render :text => "hello world", :layout => "greetings" end - + def with_ivar_in_layout @ivar = "hello world" render :text => "hello world", :layout => "ivar" @@ -66,16 +66,24 @@ module RenderText describe "Rendering text using render :text" test "rendering text from a action with default options renders the text with the layout" do - get "/render_text/simple" - assert_body "hello david" - assert_status 200 + with_routing do |set| + set.draw { match ':controller', :action => 'index' } + + get "/render_text/simple" + assert_body "hello david" + assert_status 200 + end end test "rendering text from a action with default options renders the text without the layout" do - get "/render_text/with_layout" + with_routing do |set| + set.draw { match ':controller', :action => 'index' } - assert_body "hello david" - assert_status 200 + get "/render_text/with_layout" + + assert_body "hello david" + assert_status 200 + end end test "rendering text, while also providing a custom status code" do diff --git a/actionpack/test/controller/new_base/render_xml_test.rb b/actionpack/test/controller/new_base/render_xml_test.rb index d044738a78..b8527a943d 100644 --- a/actionpack/test/controller/new_base/render_xml_test.rb +++ b/actionpack/test/controller/new_base/render_xml_test.rb @@ -1,7 +1,7 @@ require 'abstract_unit' module RenderXml - + # This has no layout and it works class BasicController < ActionController::Base self.view_paths = [ActionView::FixtureResolver.new( diff --git a/actionpack/test/controller/output_escaping_test.rb b/actionpack/test/controller/output_escaping_test.rb index 43a8c05cda..f6913a2138 100644 --- a/actionpack/test/controller/output_escaping_test.rb +++ b/actionpack/test/controller/output_escaping_test.rb @@ -3,7 +3,7 @@ require 'abstract_unit' class OutputEscapingTest < ActiveSupport::TestCase test "escape_html shouldn't die when passed nil" do - assert ERB::Util.h(nil).blank? + assert_blank ERB::Util.h(nil) end test "escapeHTML should escape strings" do diff --git a/actionpack/test/controller/record_identifier_test.rb b/actionpack/test/controller/record_identifier_test.rb index 835a0e970b..f3e5ff8a47 100644 --- a/actionpack/test/controller/record_identifier_test.rb +++ b/actionpack/test/controller/record_identifier_test.rb @@ -1,30 +1,5 @@ require 'abstract_unit' - -class Comment - extend ActiveModel::Naming - include ActiveModel::Conversion - - attr_reader :id - def to_key; id ? [id] : nil end - def save; @id = 1 end - def new_record?; @id.nil? end - def name - @id.nil? ? 'new comment' : "comment ##{@id}" - end -end - -class Sheep - extend ActiveModel::Naming - include ActiveModel::Conversion - - attr_reader :id - def to_key; id ? [id] : nil end - def save; @id = 1 end - def new_record?; @id.nil? end - def name - @id.nil? ? 'new sheep' : "sheep ##{@id}" - end -end +require 'controller/fake_models' class RecordIdentifierTest < Test::Unit::TestCase include ActionController::RecordIdentifier diff --git a/actionpack/test/controller/redirect_test.rb b/actionpack/test/controller/redirect_test.rb index 441bc47908..92d4a6d98b 100644 --- a/actionpack/test/controller/redirect_test.rb +++ b/actionpack/test/controller/redirect_test.rb @@ -3,24 +3,6 @@ require 'abstract_unit' class WorkshopsController < ActionController::Base end -class Workshop - extend ActiveModel::Naming - include ActiveModel::Conversion - attr_accessor :id - - def initialize(id) - @id = id - end - - def persisted? - id.present? - end - - def to_s - id.to_s - end -end - class RedirectController < ActionController::Base def simple_redirect redirect_to :action => "hello_world" @@ -99,6 +81,19 @@ class RedirectController < ActionController::Base redirect_to nil end + def redirect_to_with_block + redirect_to proc { "http://www.rubyonrails.org/" } + end + + def redirect_to_with_block_and_assigns + @url = "http://www.rubyonrails.org/" + redirect_to proc { @url } + end + + def redirect_to_with_block_and_options + redirect_to proc { {:action => "hello_world"} } + end + def rescue_errors(e) raise e end def rescue_action(e) raise end @@ -232,7 +227,7 @@ class RedirectTest < ActionController::TestCase def test_redirect_to_record with_routing do |set| - set.draw do |map| + set.draw do resources :workshops match ':controller/:action' end @@ -252,6 +247,31 @@ class RedirectTest < ActionController::TestCase get :redirect_to_nil end end + + def test_redirect_to_with_block + get :redirect_to_with_block + assert_response :redirect + assert_redirected_to "http://www.rubyonrails.org/" + end + + def test_redirect_to_with_block_and_assigns + get :redirect_to_with_block_and_assigns + assert_response :redirect + assert_redirected_to "http://www.rubyonrails.org/" + end + + def test_redirect_to_with_block_and_accepted_options + with_routing do |set| + set.draw do + match ':controller/:action' + end + + get :redirect_to_with_block_and_options + + assert_response :redirect + assert_redirected_to "http://test.host/redirect/hello_world" + end + end end module ModuleTest diff --git a/actionpack/test/controller/render_json_test.rb b/actionpack/test/controller/render_json_test.rb index 5958b18d80..fc604a2db3 100644 --- a/actionpack/test/controller/render_json_test.rb +++ b/actionpack/test/controller/render_json_test.rb @@ -9,6 +9,10 @@ class RenderJsonTest < ActionController::TestCase hash.except!(*options[:except]) if options[:except] hash end + + def to_json(options = {}) + super :except => [:c, :e] + end end class TestController < ActionController::Base @@ -22,6 +26,10 @@ class RenderJsonTest < ActionController::TestCase render :json => nil end + def render_json_render_to_string + render :text => render_to_string(:json => '[]') + end + def render_json_hello_world render :json => ActiveSupport::JSON.encode(:hello => 'world') end @@ -49,6 +57,10 @@ class RenderJsonTest < ActionController::TestCase def render_json_with_extra_options render :json => JsonRenderable.new, :except => [:c, :e] end + + def render_json_without_options + render :json => JsonRenderable.new + end end tests TestController @@ -68,6 +80,12 @@ class RenderJsonTest < ActionController::TestCase assert_equal 'application/json', @response.content_type end + def test_render_json_render_to_string + get :render_json_render_to_string + assert_equal '[]', @response.body + end + + def test_render_json get :render_json_hello_world assert_equal '{"hello":"world"}', @response.body @@ -109,4 +127,9 @@ class RenderJsonTest < ActionController::TestCase assert_equal '{"a":"b"}', @response.body assert_equal 'application/json', @response.content_type end + + def test_render_json_calls_to_json_from_object + get :render_json_without_options + assert_equal '{"a":"b"}', @response.body + end end diff --git a/actionpack/test/controller/render_other_test.rb b/actionpack/test/controller/render_other_test.rb index dfc4f2db8c..eda777e7a7 100644 --- a/actionpack/test/controller/render_other_test.rb +++ b/actionpack/test/controller/render_other_test.rb @@ -120,6 +120,7 @@ class RenderOtherTest < ActionController::TestCase private def default_render + @alternate_default_render ||= nil if @alternate_default_render @alternate_default_render.call else @@ -224,15 +225,15 @@ class RenderOtherTest < ActionController::TestCase get :update_page_with_instance_variables assert_template nil assert_equal 'text/javascript; charset=utf-8', @response.headers["Content-Type"] - assert_match /balance/, @response.body - assert_match /\$37/, @response.body + assert_match(/balance/, @response.body) + assert_match(/\$37/, @response.body) end def test_update_page_with_view_method get :update_page_with_view_method assert_template nil assert_equal 'text/javascript; charset=utf-8', @response.headers["Content-Type"] - assert_match /2 people/, @response.body + assert_match(/2 people/, @response.body) end def test_should_render_html_formatted_partial_with_rjs diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb index a57a12f271..be492152f2 100644 --- a/actionpack/test/controller/render_test.rb +++ b/actionpack/test/controller/render_test.rb @@ -7,7 +7,7 @@ module Fun # :ported: def hello_world end - + def nested_partial_with_form_builder render :partial => ActionView::Helpers::FormBuilder.new(:post, nil, view_context, {}, Proc.new {}) end @@ -99,11 +99,6 @@ class TestController < ActionController::Base render :template => "test/hello_world" end - def render_hello_world_with_etag_set - response.etag = "hello_world" - render :template => "test/hello_world" - end - # :ported: compatibility def render_hello_world_with_forward_slash render :template => "/test/hello_world" @@ -130,6 +125,10 @@ class TestController < ActionController::Base render :action => "hello_world" end + def render_action_upcased_hello_world + render :action => "Hello_world" + end + def render_action_hello_world_as_string render "hello_world" end @@ -276,6 +275,7 @@ class TestController < ActionController::Base # :ported: def builder_layout_test + @name = nil render :action => "hello", :layout => "layouts/builder" end @@ -327,6 +327,7 @@ class TestController < ActionController::Base end def default_render + @alternate_default_render ||= nil if @alternate_default_render @alternate_default_render.call else @@ -339,14 +340,17 @@ class TestController < ActionController::Base end def layout_test_with_different_layout + @variable_for_layout = nil render :action => "hello_world", :layout => "standard" end def layout_test_with_different_layout_and_string_action + @variable_for_layout = nil render "hello_world", :layout => "standard" end def layout_test_with_different_layout_and_symbol_action + @variable_for_layout = nil render :hello_world, :layout => "standard" end @@ -355,6 +359,7 @@ class TestController < ActionController::Base end def layout_overriding_layout + @variable_for_layout = nil render :action => "hello_world", :layout => "standard" end @@ -488,6 +493,10 @@ class TestController < ActionController::Base head :x_custom_header => "something" end + def head_with_www_authenticate_header + head 'WWW-Authenticate' => 'something' + end + def head_with_status_code_first head :forbidden, :x_custom_header => "something" end @@ -639,6 +648,7 @@ class TestController < ActionController::Base private def determine_layout + @variable_for_layout ||= nil case action_name when "hello_world", "layout_test", "rendering_without_layout", "rendering_nothing_on_layout", "render_text_hello_world", @@ -736,6 +746,12 @@ class RenderTest < ActionController::TestCase assert_template "test/hello_world" end + def test_render_action_upcased + assert_raise ActionView::MissingTemplate do + get :render_action_upcased_hello_world + end + end + # :ported: def test_render_action_hello_world_as_string get :render_action_hello_world_as_string @@ -1016,7 +1032,7 @@ class RenderTest < ActionController::TestCase assert_equal " ", @response.body end - def test_render_to_string + def test_render_to_string_not_deprecated assert_not_deprecated { get :hello_in_a_string } assert_equal "How's there? goodbyeHello: davidHello: marygoodbye\n", @response.body end @@ -1113,20 +1129,20 @@ class RenderTest < ActionController::TestCase def test_head_with_location_header get :head_with_location_header - assert @response.body.blank? + assert_blank @response.body assert_equal "/foo", @response.headers["Location"] assert_response :ok end def test_head_with_location_object with_routing do |set| - set.draw do |map| + set.draw do resources :customers match ':controller/:action' end get :head_with_location_object - assert @response.body.blank? + assert_blank @response.body assert_equal "http://www.nextangle.com/customers/1", @response.headers["Location"] assert_response :ok end @@ -1134,11 +1150,18 @@ class RenderTest < ActionController::TestCase def test_head_with_custom_header get :head_with_custom_header - assert @response.body.blank? + assert_blank @response.body assert_equal "something", @response.headers["X-Custom-Header"] assert_response :ok end + def test_head_with_www_authenticate_header + get :head_with_www_authenticate_header + assert_blank @response.body + assert_equal "something", @response.headers["WWW-Authenticate"] + assert_response :ok + end + def test_head_with_symbolic_status get :head_with_symbolic_status, :status => "ok" assert_equal 200, @response.status @@ -1234,7 +1257,7 @@ class RenderTest < ActionController::TestCase assert_match(/<label/, @response.body) assert_template('test/_labelling_form') end - + def test_nested_partial_with_form_builder @controller = Fun::GamesController.new get :nested_partial_with_form_builder @@ -1368,119 +1391,6 @@ class ExpiresInRenderTest < ActionController::TestCase end end - -class EtagRenderTest < ActionController::TestCase - tests TestController - - def setup - super - @request.host = "www.nextangle.com" - @expected_bang_etag = etag_for(expand_key([:foo, 123])) - end - - def test_render_blank_body_shouldnt_set_etag - get :blank_response - assert !@response.etag? - end - - def test_render_200_should_set_etag - get :render_hello_world_from_variable - assert_equal etag_for("hello david"), @response.headers['ETag'] - assert_equal "max-age=0, private, must-revalidate", @response.headers['Cache-Control'] - end - - def test_render_against_etag_request_should_304_when_match - @request.if_none_match = etag_for("hello david") - get :render_hello_world_from_variable - assert_equal 304, @response.status.to_i - assert @response.body.empty? - end - - def test_render_against_etag_request_should_have_no_content_length_when_match - @request.if_none_match = etag_for("hello david") - get :render_hello_world_from_variable - assert !@response.headers.has_key?("Content-Length") - end - - def test_render_against_etag_request_should_200_when_no_match - @request.if_none_match = etag_for("hello somewhere else") - get :render_hello_world_from_variable - assert_equal 200, @response.status.to_i - assert !@response.body.empty? - end - - def test_render_should_not_set_etag_when_last_modified_has_been_specified - get :render_hello_world_with_last_modified_set - assert_equal 200, @response.status.to_i - assert_not_nil @response.last_modified - assert_nil @response.etag - assert @response.body.present? - end - - def test_render_with_etag - get :render_hello_world_from_variable - expected_etag = etag_for('hello david') - assert_equal expected_etag, @response.headers['ETag'] - @response = ActionController::TestResponse.new - - @request.if_none_match = expected_etag - get :render_hello_world_from_variable - assert_equal 304, @response.status.to_i - - @response = ActionController::TestResponse.new - @request.if_none_match = "\"diftag\"" - get :render_hello_world_from_variable - assert_equal 200, @response.status.to_i - end - - def render_with_404_shouldnt_have_etag - get :render_custom_code - assert_nil @response.headers['ETag'] - end - - def test_etag_should_not_be_changed_when_already_set - get :render_hello_world_with_etag_set - assert_equal etag_for("hello_world"), @response.headers['ETag'] - end - - def test_etag_should_govern_renders_with_layouts_too - get :builder_layout_test - assert_equal "<wrapper>\n<html>\n <p>Hello </p>\n<p>This is grand!</p>\n</html>\n</wrapper>\n", @response.body - assert_equal etag_for("<wrapper>\n<html>\n <p>Hello </p>\n<p>This is grand!</p>\n</html>\n</wrapper>\n"), @response.headers['ETag'] - end - - def test_etag_with_bang_should_set_etag - get :conditional_hello_with_bangs - assert_equal @expected_bang_etag, @response.headers["ETag"] - assert_response :success - end - - def test_etag_with_bang_should_obey_if_none_match - @request.if_none_match = @expected_bang_etag - get :conditional_hello_with_bangs - assert_response :not_modified - end - - def test_etag_with_public_true_should_set_header - get :conditional_hello_with_public_header - assert_equal "public", @response.headers['Cache-Control'] - end - - def test_etag_with_public_true_should_set_header_and_retain_other_headers - get :conditional_hello_with_public_header_and_expires_at - assert_equal "max-age=60, public", @response.headers['Cache-Control'] - end - - protected - def etag_for(text) - %("#{Digest::MD5.hexdigest(text)}") - end - - def expand_key(args) - ActiveSupport::Cache.expand_cache_key(args) - end -end - class LastModifiedRenderTest < ActionController::TestCase tests TestController @@ -1499,7 +1409,7 @@ class LastModifiedRenderTest < ActionController::TestCase @request.if_modified_since = @last_modified get :conditional_hello assert_equal 304, @response.status.to_i - assert @response.body.blank?, @response.body + assert_blank @response.body assert_equal @last_modified, @response.headers['Last-Modified'] end @@ -1514,7 +1424,7 @@ class LastModifiedRenderTest < ActionController::TestCase @request.if_modified_since = 'Thu, 16 Jul 2008 00:00:00 GMT' get :conditional_hello assert_equal 200, @response.status.to_i - assert !@response.body.blank? + assert_present @response.body assert_equal @last_modified, @response.headers['Last-Modified'] end diff --git a/actionpack/test/controller/render_xml_test.rb b/actionpack/test/controller/render_xml_test.rb index 4bf867fa41..ec4dc848ff 100644 --- a/actionpack/test/controller/render_xml_test.rb +++ b/actionpack/test/controller/render_xml_test.rb @@ -70,10 +70,9 @@ class RenderXmlTest < ActionController::TestCase def test_rendering_with_object_location_should_set_header_with_url_for with_routing do |set| - set.draw do |map| + set.draw do resources :customers - # match ':controller/:action' - map.connect ':controller/:action/:id' + match ':controller/:action' end get :render_with_object_location diff --git a/actionpack/test/controller/request/test_request_test.rb b/actionpack/test/controller/request/test_request_test.rb index 0a39feb7fe..e624f11773 100644 --- a/actionpack/test/controller/request/test_request_test.rb +++ b/actionpack/test/controller/request/test_request_test.rb @@ -29,8 +29,7 @@ class ActionController::TestRequestTest < ActiveSupport::TestCase end def test_session_id_different_on_each_call - prev_id = assert_not_equal(@request.session_options[:id], ActionController::TestRequest.new.session_options[:id]) end -end
\ No newline at end of file +end diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb index be05ef6167..d520b5e512 100644 --- a/actionpack/test/controller/request_forgery_protection_test.rb +++ b/actionpack/test/controller/request_forgery_protection_test.rb @@ -1,5 +1,6 @@ require 'abstract_unit' require 'digest/sha1' +require 'active_support/core_ext/string/strip' # common controller actions module RequestForgeryProtectionActions @@ -11,12 +12,28 @@ module RequestForgeryProtectionActions render :inline => "<%= button_to('New', '/') {} %>" end + def external_form + render :inline => "<%= form_tag('http://farfar.away/form', :authenticity_token => 'external_token') {} %>" + end + + def external_form_without_protection + render :inline => "<%= form_tag('http://farfar.away/form', :authenticity_token => false) {} %>" + end + def unsafe render :text => 'pwn' end def meta - render :inline => "<%= csrf_meta_tag %>" + render :inline => "<%= csrf_meta_tags %>" + end + + def external_form_for + render :inline => "<%= form_for(:some_resource, :authenticity_token => 'external_token') {} %>" + end + + def form_for_without_protection + render :inline => "<%= form_for(:some_resource, :authenticity_token => false ) {} %>" end def rescue_action(e) raise e end @@ -28,6 +45,16 @@ class RequestForgeryProtectionController < ActionController::Base protect_from_forgery :only => %w(index meta) end +class RequestForgeryProtectionControllerUsingOldBehaviour < ActionController::Base + include RequestForgeryProtectionActions + protect_from_forgery :only => %w(index meta) + + def handle_unverified_request + raise(ActionController::InvalidAuthenticityToken) + end +end + + class FreeCookieController < RequestForgeryProtectionController self.allow_forgery_protection = false @@ -50,153 +77,92 @@ end # common test methods module RequestForgeryProtectionTests - def teardown - ActionController::Base.request_forgery_protection_token = nil - end - - - def test_should_render_form_with_token_tag - get :index - assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token - end - - def test_should_render_button_to_with_token_tag - get :show_button - assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token - end - - def test_should_allow_get - get :index - assert_response :success - end - - def test_should_allow_post_without_token_on_unsafe_action - post :unsafe - assert_response :success - end - - def test_should_not_allow_html_post_without_token - @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s - assert_raise(ActionController::InvalidAuthenticityToken) { post :index, :format => :html } - end - - def test_should_not_allow_html_put_without_token - @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s - assert_raise(ActionController::InvalidAuthenticityToken) { put :index, :format => :html } - end - - def test_should_not_allow_html_delete_without_token - @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s - assert_raise(ActionController::InvalidAuthenticityToken) { delete :index, :format => :html } - end + def setup + @token = "cf50faa3fe97702ca1ae" - def test_should_allow_api_formatted_post_without_token - assert_nothing_raised do - post :index, :format => 'xml' - end + ActiveSupport::SecureRandom.stubs(:base64).returns(@token) + ActionController::Base.request_forgery_protection_token = :authenticity_token end - def test_should_not_allow_api_formatted_put_without_token - assert_nothing_raised do - put :index, :format => 'xml' - end - end - def test_should_allow_api_formatted_delete_without_token - assert_nothing_raised do - delete :index, :format => 'xml' + def test_should_render_form_with_token_tag + assert_not_blocked do + get :index end + assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token end - def test_should_not_allow_api_formatted_post_sent_as_url_encoded_form_without_token - assert_raise(ActionController::InvalidAuthenticityToken) do - @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s - post :index, :format => 'xml' + def test_should_render_button_to_with_token_tag + assert_not_blocked do + get :show_button end + assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token end - def test_should_not_allow_api_formatted_put_sent_as_url_encoded_form_without_token - assert_raise(ActionController::InvalidAuthenticityToken) do - @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s - put :index, :format => 'xml' - end + def test_should_allow_get + assert_not_blocked { get :index } end - def test_should_not_allow_api_formatted_delete_sent_as_url_encoded_form_without_token - assert_raise(ActionController::InvalidAuthenticityToken) do - @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s - delete :index, :format => 'xml' - end + def test_should_allow_post_without_token_on_unsafe_action + assert_not_blocked { post :unsafe } end - def test_should_not_allow_api_formatted_post_sent_as_multipart_form_without_token - assert_raise(ActionController::InvalidAuthenticityToken) do - @request.env['CONTENT_TYPE'] = Mime::MULTIPART_FORM.to_s - post :index, :format => 'xml' - end + def test_should_not_allow_post_without_token + assert_blocked { post :index } end - def test_should_not_allow_api_formatted_put_sent_as_multipart_form_without_token - assert_raise(ActionController::InvalidAuthenticityToken) do - @request.env['CONTENT_TYPE'] = Mime::MULTIPART_FORM.to_s - put :index, :format => 'xml' - end + def test_should_not_allow_post_without_token_irrespective_of_format + assert_blocked { post :index, :format=>'xml' } end - def test_should_not_allow_api_formatted_delete_sent_as_multipart_form_without_token - assert_raise(ActionController::InvalidAuthenticityToken) do - @request.env['CONTENT_TYPE'] = Mime::MULTIPART_FORM.to_s - delete :index, :format => 'xml' - end + def test_should_not_allow_put_without_token + assert_blocked { put :index } end - def test_should_allow_xhr_post_without_token - assert_nothing_raised { xhr :post, :index } + def test_should_not_allow_delete_without_token + assert_blocked { delete :index } end - def test_should_allow_xhr_put_without_token - assert_nothing_raised { xhr :put, :index } + def test_should_not_allow_xhr_post_without_token + assert_blocked { xhr :post, :index } end - def test_should_allow_xhr_delete_without_token - assert_nothing_raised { xhr :delete, :index } + def test_should_allow_post_with_token + assert_not_blocked { post :index, :authenticity_token => @token } end - def test_should_allow_xhr_post_with_encoded_form_content_type_without_token - @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s - assert_nothing_raised { xhr :post, :index } + def test_should_allow_put_with_token + assert_not_blocked { put :index, :authenticity_token => @token } end - def test_should_allow_post_with_token - post :index, :authenticity_token => @token - assert_response :success + def test_should_allow_delete_with_token + assert_not_blocked { delete :index, :authenticity_token => @token } end - def test_should_allow_put_with_token - put :index, :authenticity_token => @token - assert_response :success + def test_should_allow_post_with_token_in_header + @request.env['HTTP_X_CSRF_TOKEN'] = @token + assert_not_blocked { post :index } end - def test_should_allow_delete_with_token - delete :index, :authenticity_token => @token - assert_response :success + def test_should_allow_delete_with_token_in_header + @request.env['HTTP_X_CSRF_TOKEN'] = @token + assert_not_blocked { delete :index } end - def test_should_allow_post_with_xml - @request.env['CONTENT_TYPE'] = Mime::XML.to_s - post :index, :format => 'xml' - assert_response :success + def test_should_allow_put_with_token_in_header + @request.env['HTTP_X_CSRF_TOKEN'] = @token + assert_not_blocked { put :index } end - def test_should_allow_put_with_xml - @request.env['CONTENT_TYPE'] = Mime::XML.to_s - put :index, :format => 'xml' + def assert_blocked + session[:something_like_user_id] = 1 + yield + assert_nil session[:something_like_user_id], "session values are still present" assert_response :success end - def test_should_allow_delete_with_xml - @request.env['CONTENT_TYPE'] = Mime::XML.to_s - delete :index, :format => 'xml' + def assert_not_blocked + assert_nothing_raised { yield } assert_response :success end end @@ -205,21 +171,23 @@ end class RequestForgeryProtectionControllerTest < ActionController::TestCase include RequestForgeryProtectionTests - def setup - @controller = RequestForgeryProtectionController.new - @request = ActionController::TestRequest.new - @request.format = :html - @response = ActionController::TestResponse.new - @token = "cf50faa3fe97702ca1ae" - - ActiveSupport::SecureRandom.stubs(:base64).returns(@token) - ActionController::Base.request_forgery_protection_token = :authenticity_token - end test 'should emit a csrf-token meta tag' do ActiveSupport::SecureRandom.stubs(:base64).returns(@token + '<=?') get :meta - assert_equal %(<meta name="csrf-param" content="authenticity_token"/>\n<meta name="csrf-token" content="cf50faa3fe97702ca1ae<=?"/>), @response.body + assert_equal <<-METAS.strip_heredoc.chomp, @response.body + <meta name="csrf-param" content="authenticity_token"/> + <meta name="csrf-token" content="cf50faa3fe97702ca1ae<=?"/> + METAS + end +end + +class RequestForgeryProtectionControllerUsingOldBehaviourTest < ActionController::TestCase + include RequestForgeryProtectionTests + def assert_blocked + assert_raises(ActionController::InvalidAuthenticityToken) do + yield + end end end @@ -251,17 +219,27 @@ class FreeCookieControllerTest < ActionController::TestCase test 'should not emit a csrf-token meta tag' do get :meta - assert @response.body.blank? + assert_blank @response.body end end + + + + class CustomAuthenticityParamControllerTest < ActionController::TestCase def setup + ActionController::Base.request_forgery_protection_token = :custom_token_name + super + end + + def teardown ActionController::Base.request_forgery_protection_token = :authenticity_token + super end def test_should_allow_custom_token - post :index, :authenticity_token => 'foobar' + post :index, :custom_token_name => 'foobar' assert_response :ok end end diff --git a/actionpack/test/controller/rescue_test.rb b/actionpack/test/controller/rescue_test.rb index a24de62b19..c445285538 100644 --- a/actionpack/test/controller/rescue_test.rb +++ b/actionpack/test/controller/rescue_test.rb @@ -1,19 +1,5 @@ require 'abstract_unit' -module ActionDispatch - class ShowExceptions - private - def public_path - "#{FIXTURE_LOAD_PATH}/public" - end - - # Silence logger - def logger - nil - end - end -end - class RescueController < ActionController::Base class NotAuthorized < StandardError end @@ -149,7 +135,7 @@ class RescueController < ActionController::Base def missing_template end - + def io_error_in_view raise ActionView::TemplateError.new(nil, {}, IOError.new('this is io error')) end @@ -311,7 +297,7 @@ class RescueControllerTest < ActionController::TestCase end end -class RescueTest < ActionController::IntegrationTest +class RescueTest < ActionDispatch::IntegrationTest class TestController < ActionController::Base class RecordInvalid < StandardError def message @@ -371,7 +357,7 @@ class RescueTest < ActionController::IntegrationTest private def with_test_routing with_routing do |set| - set.draw do |map| + set.draw do match 'foo', :to => ::RescueTest::TestController.action(:foo) match 'invalid', :to => ::RescueTest::TestController.action(:invalid) match 'b00m', :to => ::RescueTest::TestController.action(:b00m) diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb index 6c8f470fba..acb4617a60 100644 --- a/actionpack/test/controller/resources_test.rb +++ b/actionpack/test/controller/resources_test.rb @@ -1,5 +1,6 @@ -require 'active_support/core_ext/object/try' require 'abstract_unit' +require 'active_support/core_ext/object/try' +require 'active_support/core_ext/object/with_options' class ResourcesController < ActionController::Base def index() render :nothing => true end @@ -32,36 +33,6 @@ module Backoffice end class ResourcesTest < ActionController::TestCase - def test_should_arrange_actions - resource = ActionDispatch::Routing::DeprecatedMapper::Resource.new(:messages, { - :collection => { :rss => :get, :reorder => :post, :csv => :post }, - :member => { :rss => :get, :atom => :get, :upload => :post, :fix => :post }, - :new => { :preview => :get, :draft => :get }}, {}) - - assert_resource_methods [:rss], resource, :collection, :get - assert_resource_methods [:csv, :reorder], resource, :collection, :post - assert_resource_methods [:edit, :rss, :atom], resource, :member, :get - assert_resource_methods [:upload, :fix], resource, :member, :post - assert_resource_methods [:new, :preview, :draft], resource, :new, :get - end - - def test_should_resource_controller_name_equal_resource_name_by_default - resource = ActionDispatch::Routing::DeprecatedMapper::Resource.new(:messages, {}, {}) - assert_equal 'messages', resource.controller - end - - def test_should_resource_controller_name_equal_controller_option - resource = ActionDispatch::Routing::DeprecatedMapper::Resource.new(:messages, {:controller => 'posts'}, {}) - assert_equal 'posts', resource.controller - end - - def test_should_all_singleton_paths_be_the_same - [ :path, :nesting_path_prefix, :member_path ].each do |method| - resource = ActionDispatch::Routing::DeprecatedMapper::SingletonResource.new(:messages, {:path_prefix => 'admin'}, {}) - assert_equal 'admin/messages', resource.send(method) - end - end - def test_default_restful_routes with_restful_routing :messages do assert_simply_restful_for :messages @@ -69,9 +40,9 @@ class ResourcesTest < ActionController::TestCase end def test_override_paths_for_member_and_collection_methods - collection_methods = { 'rss' => :get, 'reorder' => :post, 'csv' => :post } - member_methods = { 'rss' => :get, :atom => :get, :upload => :post, :fix => :post } - path_names = {:new => 'nuevo', 'rss' => 'canal', :fix => 'corrigir' } + collection_methods = { :rss => :get, :reorder => :post, :csv => :post } + member_methods = { :rss => :get, :atom => :get, :upload => :post, :fix => :post } + path_names = {:new => 'nuevo', :rss => 'canal', :fix => 'corrigir' } with_restful_routing :messages, :collection => collection_methods, @@ -89,7 +60,7 @@ class ResourcesTest < ActionController::TestCase end collection_methods.each do |action, method| - assert_recognizes(options.merge(:action => action), + assert_recognizes(options.merge(:action => action.to_s), :path => "/messages/#{path_names[action] || action}", :method => method) end @@ -112,12 +83,6 @@ class ResourcesTest < ActionController::TestCase end end - def test_override_paths_for_default_restful_actions - resource = ActionDispatch::Routing::DeprecatedMapper::Resource.new(:messages, { - :path_names => {:new => 'nuevo', :edit => 'editar'}}, {}) - assert_equal resource.new_path, "#{resource.path}/nuevo" - end - def test_multiple_default_restful_routes with_restful_routing :messages, :comments do assert_simply_restful_for :messages @@ -131,7 +96,7 @@ class ResourcesTest < ActionController::TestCase end end - def test_irregular_id_with_no_requirements_should_raise_error + def test_irregular_id_with_no_constraints_should_raise_error expected_options = {:controller => 'messages', :action => 'show', :id => '1.1.1'} with_restful_routing :messages do @@ -141,25 +106,25 @@ class ResourcesTest < ActionController::TestCase end end - def test_irregular_id_with_requirements_should_pass + def test_irregular_id_with_constraints_should_pass expected_options = {:controller => 'messages', :action => 'show', :id => '1.1.1'} - with_restful_routing(:messages, :requirements => {:id => /[0-9]\.[0-9]\.[0-9]/}) do + with_restful_routing(:messages, :constraints => {:id => /[0-9]\.[0-9]\.[0-9]/}) do assert_recognizes(expected_options, :path => 'messages/1.1.1', :method => :get) end end - def test_with_path_prefix_requirements + def test_with_path_prefix_constraints expected_options = {:controller => 'messages', :action => 'show', :thread_id => '1.1.1', :id => '1'} - with_restful_routing :messages, :path_prefix => '/thread/:thread_id', :requirements => {:thread_id => /[0-9]\.[0-9]\.[0-9]/} do + with_restful_routing :messages, :path_prefix => '/thread/:thread_id', :constraints => {:thread_id => /[0-9]\.[0-9]\.[0-9]/} do assert_recognizes(expected_options, :path => 'thread/1.1.1/messages/1', :method => :get) end end - def test_irregular_id_requirements_should_get_passed_to_member_actions + def test_irregular_id_constraints_should_get_passed_to_member_actions expected_options = {:controller => 'messages', :action => 'custom', :id => '1.1.1'} - with_restful_routing(:messages, :member => {:custom => :get}, :requirements => {:id => /[0-9]\.[0-9]\.[0-9]/}) do + with_restful_routing(:messages, :member => {:custom => :get}, :constraints => {:id => /[0-9]\.[0-9]\.[0-9]/}) do assert_recognizes(expected_options, :path => 'messages/1.1.1/custom', :method => :get) end end @@ -178,7 +143,7 @@ class ResourcesTest < ActionController::TestCase end def test_with_name_prefix - with_restful_routing :messages, :name_prefix => 'post_' do + with_restful_routing :messages, :as => 'post_messages' do assert_simply_restful_for :messages, :name_prefix => 'post_' end end @@ -186,7 +151,16 @@ class ResourcesTest < ActionController::TestCase def test_with_collection_actions actions = { 'a' => :get, 'b' => :put, 'c' => :post, 'd' => :delete } - with_restful_routing :messages, :collection => actions do + with_routing do |set| + set.draw do + resources :messages do + get :a, :on => :collection + put :b, :on => :collection + post :c, :on => :collection + delete :d, :on => :collection + end + end + assert_restful_routes_for :messages do |options| actions.each do |action, method| assert_recognizes(options.merge(:action => action), :path => "/messages/#{action}", :method => method) @@ -204,7 +178,18 @@ class ResourcesTest < ActionController::TestCase def test_with_collection_actions_and_name_prefix actions = { 'a' => :get, 'b' => :put, 'c' => :post, 'd' => :delete } - with_restful_routing :messages, :path_prefix => '/threads/:thread_id', :name_prefix => "thread_", :collection => actions do + with_routing do |set| + set.draw do + scope '/threads/:thread_id' do + resources :messages, :as => 'thread_messages' do + get :a, :on => :collection + put :b, :on => :collection + post :c, :on => :collection + delete :d, :on => :collection + end + end + end + assert_restful_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options| actions.each do |action, method| assert_recognizes(options.merge(:action => action), :path => "/threads/1/messages/#{action}", :method => method) @@ -222,7 +207,16 @@ class ResourcesTest < ActionController::TestCase def test_with_collection_actions_and_name_prefix_and_member_action_with_same_name actions = { 'a' => :get } - with_restful_routing :messages, :path_prefix => '/threads/:thread_id', :name_prefix => "thread_", :collection => actions, :member => actions do + with_routing do |set| + set.draw do + scope '/threads/:thread_id' do + resources :messages, :as => 'thread_messages' do + get :a, :on => :collection + get :a, :on => :member + end + end + end + assert_restful_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options| actions.each do |action, method| assert_recognizes(options.merge(:action => action), :path => "/threads/1/messages/#{action}", :method => method) @@ -240,7 +234,18 @@ class ResourcesTest < ActionController::TestCase def test_with_collection_action_and_name_prefix_and_formatted actions = { 'a' => :get, 'b' => :put, 'c' => :post, 'd' => :delete } - with_restful_routing :messages, :path_prefix => '/threads/:thread_id', :name_prefix => "thread_", :collection => actions do + with_routing do |set| + set.draw do + scope '/threads/:thread_id' do + resources :messages, :as => 'thread_messages' do + get :a, :on => :collection + put :b, :on => :collection + post :c, :on => :collection + delete :d, :on => :collection + end + end + end + assert_restful_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options| actions.each do |action, method| assert_recognizes(options.merge(:action => action, :format => 'xml'), :path => "/threads/1/messages/#{action}.xml", :method => method) @@ -274,7 +279,7 @@ class ResourcesTest < ActionController::TestCase def test_with_member_action_and_requirement expected_options = {:controller => 'messages', :action => 'mark', :id => '1.1.1'} - with_restful_routing(:messages, :requirements => {:id => /[0-9]\.[0-9]\.[0-9]/}, :member => { :mark => :get }) do + with_restful_routing(:messages, :constraints => {:id => /[0-9]\.[0-9]\.[0-9]/}, :member => { :mark => :get }) do assert_recognizes(expected_options, :path => 'messages/1.1.1/mark', :method => :get) end end @@ -296,31 +301,18 @@ class ResourcesTest < ActionController::TestCase end end - # def test_member_when_changed_default_restful_actions_and_path_names_not_specified - # default_path_names = ActionController::Base.resources_path_names - # ActionController::Base.resources_path_names = {:new => 'nuevo', :edit => 'editar'} - # - # with_restful_routing :messages do - # new_options = { :action => 'new', :controller => 'messages' } - # new_path = "/messages/nuevo" - # edit_options = { :action => 'edit', :id => '1', :controller => 'messages' } - # edit_path = "/messages/1/editar" - # - # assert_restful_routes_for :messages do |options| - # assert_recognizes(options.merge(new_options), :path => new_path, :method => :get) - # end - # - # assert_restful_routes_for :messages do |options| - # assert_recognizes(options.merge(edit_options), :path => edit_path, :method => :get) - # end - # end - # ensure - # ActionController::Base.resources_path_names = default_path_names - # end - def test_with_two_member_actions_with_same_method [:put, :post].each do |method| - with_restful_routing :messages, :member => { :mark => method, :unmark => method } do + with_routing do |set| + set.draw do + resources :messages do + member do + match :mark , :via => method + match :unmark, :via => method + end + end + end + %w(mark unmark).each do |action| action_options = {:action => action, :id => '1'} action_path = "/messages/1/#{action}" @@ -337,7 +329,19 @@ class ResourcesTest < ActionController::TestCase end def test_array_as_collection_or_member_method_value - with_restful_routing :messages, :collection => { :search => [:get, :post] }, :member => { :toggle => [:get, :post] } do + with_routing do |set| + set.draw do + resources :messages do + collection do + match :search, :via => [:post, :get] + end + + member do + match :toggle, :via => [:post, :get] + end + end + end + assert_restful_routes_for :messages do |options| [:get, :post].each do |method| assert_recognizes(options.merge(:action => 'search'), :path => "/messages/search", :method => method) @@ -350,7 +354,13 @@ class ResourcesTest < ActionController::TestCase end def test_with_new_action - with_restful_routing :messages, :new => { :preview => :post } do + with_routing do |set| + set.draw do + resources :messages do + post :preview, :on => :new + end + end + preview_options = {:action => 'preview'} preview_path = "/messages/new/preview" assert_restful_routes_for :messages do |options| @@ -364,7 +374,15 @@ class ResourcesTest < ActionController::TestCase end def test_with_new_action_with_name_prefix - with_restful_routing :messages, :new => { :preview => :post }, :path_prefix => '/threads/:thread_id', :name_prefix => 'thread_' do + with_routing do |set| + set.draw do + scope('/threads/:thread_id') do + resources :messages, :as => "thread_messages" do + post :preview, :on => :new + end + end + end + preview_options = {:action => 'preview', :thread_id => '1'} preview_path = "/threads/1/messages/new/preview" assert_restful_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options| @@ -378,7 +396,15 @@ class ResourcesTest < ActionController::TestCase end def test_with_formatted_new_action_with_name_prefix - with_restful_routing :messages, :new => { :preview => :post }, :path_prefix => '/threads/:thread_id', :name_prefix => 'thread_' do + with_routing do |set| + set.draw do + scope('/threads/:thread_id') do + resources :messages, :as => "thread_messages" do + post :preview, :on => :new + end + end + end + preview_options = {:action => 'preview', :thread_id => '1', :format => 'xml'} preview_path = "/threads/1/messages/new/preview.xml" assert_restful_routes_for :messages, :path_prefix => 'threads/1/', :name_prefix => 'thread_', :options => { :thread_id => '1' } do |options| @@ -401,7 +427,13 @@ class ResourcesTest < ActionController::TestCase end end - with_restful_routing :messages, :new => { :new => :any } do + with_routing do |set| + set.draw do + resources :messages do + match :new, :via => [:post, :get], :on => :new + end + end + assert_restful_routes_for :messages do |options| assert_recognizes(options.merge(:action => "new"), :path => "/messages/new", :method => :post) assert_recognizes(options.merge(:action => "new"), :path => "/messages/new", :method => :get) @@ -411,10 +443,10 @@ class ResourcesTest < ActionController::TestCase def test_nested_restful_routes with_routing do |set| - set.draw do |map| - map.resources :threads do |map| - map.resources :messages do |map| - map.resources :comments + set.draw do + resources :threads do + resources :messages do + resources :comments end end end @@ -431,32 +463,12 @@ class ResourcesTest < ActionController::TestCase end end - def test_nested_restful_routes_with_overwritten_defaults - with_routing do |set| - set.draw do |map| - map.resources :threads do |map| - map.resources :messages, :name_prefix => nil do |map| - map.resources :comments, :name_prefix => nil - end - end - end - - assert_simply_restful_for :threads - assert_simply_restful_for :messages, - :path_prefix => 'threads/1/', - :options => { :thread_id => '1' } - assert_simply_restful_for :comments, - :path_prefix => 'threads/1/messages/2/', - :options => { :thread_id => '1', :message_id => '2' } - end - end - def test_shallow_nested_restful_routes with_routing do |set| - set.draw do |map| - map.resources :threads, :shallow => true do |map| - map.resources :messages do |map| - map.resources :comments + set.draw do + resources :threads, :shallow => true do + resources :messages do + resources :comments end end end @@ -478,11 +490,11 @@ class ResourcesTest < ActionController::TestCase def test_shallow_nested_restful_routes_with_namespaces with_routing do |set| - set.draw do |map| - map.namespace :backoffice do |map| - map.namespace :admin do |map| - map.resources :products, :shallow => true do |map| - map.resources :images + set.draw do + namespace :backoffice do + namespace :admin do + resources :products, :shallow => true do + resources :images end end end @@ -531,9 +543,9 @@ class ResourcesTest < ActionController::TestCase def test_should_create_nested_singleton_resource_routes with_routing do |set| - set.draw do |map| - map.resource :admin, :controller => 'admin' do |admin| - admin.resource :account + set.draw do + resource :admin, :controller => 'admin' do + resource :account end end @@ -542,69 +554,15 @@ class ResourcesTest < ActionController::TestCase end end - def test_resource_has_many_should_become_nested_resources - with_routing do |set| - set.draw do |map| - map.resources :messages, :has_many => [ :comments, :authors ] - end - - assert_simply_restful_for :messages - assert_simply_restful_for :comments, :name_prefix => "message_", :path_prefix => 'messages/1/', :options => { :message_id => '1' } - assert_simply_restful_for :authors, :name_prefix => "message_", :path_prefix => 'messages/1/', :options => { :message_id => '1' } - end - end - - def test_resources_has_many_hash_should_become_nested_resources - with_routing do |set| - set.draw do |map| - map.resources :threads, :has_many => { :messages => [ :comments, { :authors => :threads } ] } - end - - assert_simply_restful_for :threads - assert_simply_restful_for :messages, :name_prefix => "thread_", :path_prefix => 'threads/1/', :options => { :thread_id => '1' } - assert_simply_restful_for :comments, :name_prefix => "thread_message_", :path_prefix => 'threads/1/messages/1/', :options => { :thread_id => '1', :message_id => '1' } - assert_simply_restful_for :authors, :name_prefix => "thread_message_", :path_prefix => 'threads/1/messages/1/', :options => { :thread_id => '1', :message_id => '1' } - assert_simply_restful_for :threads, :name_prefix => "thread_message_author_", :path_prefix => 'threads/1/messages/1/authors/1/', :options => { :thread_id => '1', :message_id => '1', :author_id => '1' } - end - end - - def test_shallow_resource_has_many_should_become_shallow_nested_resources - with_routing do |set| - set.draw do |map| - map.resources :messages, :has_many => [ :comments, :authors ], :shallow => true - end - - assert_simply_restful_for :messages, :shallow => true - assert_simply_restful_for :comments, :name_prefix => "message_", :path_prefix => 'messages/1/', :shallow => true, :options => { :message_id => '1' } - assert_simply_restful_for :authors, :name_prefix => "message_", :path_prefix => 'messages/1/', :shallow => true, :options => { :message_id => '1' } - end - end - - def test_resource_has_one_should_become_nested_resources - with_routing do |set| - set.draw do |map| - map.resources :messages, :has_one => :logo - end - - assert_simply_restful_for :messages - assert_singleton_restful_for :logo, :name_prefix => 'message_', :path_prefix => 'messages/1/', :options => { :message_id => '1' } - end - end - - def test_shallow_resource_has_one_should_become_shallow_nested_resources - with_routing do |set| - set.draw do |map| - map.resources :messages, :has_one => :logo, :shallow => true - end - - assert_simply_restful_for :messages, :shallow => true - assert_singleton_restful_for :logo, :name_prefix => 'message_', :path_prefix => 'messages/1/', :shallow => true, :options => { :message_id => '1' } - end - end - def test_singleton_resource_with_member_action [:put, :post].each do |method| - with_singleton_resources :account, :member => { :reset => method } do + with_routing do |set| + set.draw do + resource :account do + match :reset, :on => :member, :via => method + end + end + reset_options = {:action => 'reset'} reset_path = "/account/reset" assert_singleton_routes_for :account do |options| @@ -620,7 +578,14 @@ class ResourcesTest < ActionController::TestCase def test_singleton_resource_with_two_member_actions_with_same_method [:put, :post].each do |method| - with_singleton_resources :account, :member => { :reset => method, :disable => method } do + with_routing do |set| + set.draw do + resource :account do + match :reset, :on => :member, :via => method + match :disable, :on => :member, :via => method + end + end + %w(reset disable).each do |action| action_options = {:action => action} action_path = "/account/#{action}" @@ -638,9 +603,9 @@ class ResourcesTest < ActionController::TestCase def test_should_nest_resources_in_singleton_resource with_routing do |set| - set.draw do |map| - map.resource :account do |account| - account.resources :messages + set.draw do + resource :account do + resources :messages end end @@ -649,11 +614,13 @@ class ResourcesTest < ActionController::TestCase end end - def test_should_nest_resources_in_singleton_resource_with_path_prefix + def test_should_nest_resources_in_singleton_resource_with_path_scope with_routing do |set| - set.draw do |map| - map.resource(:account, :path_prefix => ':site_id') do |account| - account.resources :messages + set.draw do + scope ':site_id' do + resource(:account) do + resources :messages + end end end @@ -664,9 +631,9 @@ class ResourcesTest < ActionController::TestCase def test_should_nest_singleton_resource_in_resources with_routing do |set| - set.draw do |map| - map.resources :threads do |thread| - thread.resource :admin, :controller => 'admin' + set.draw do + resources :threads do + resource :admin, :controller => 'admin' end end @@ -691,52 +658,18 @@ class ResourcesTest < ActionController::TestCase end end - def test_should_not_allow_invalid_head_method_for_member_routes - with_routing do |set| - assert_raise(ArgumentError) do - set.draw do |map| - map.resources :messages, :member => {:something => :head} - end - end - end - end - - def test_should_not_allow_invalid_http_methods_for_member_routes + def test_new_style_named_routes_for_resource with_routing do |set| - assert_raise(ArgumentError) do - set.draw do |map| - map.resources :messages, :member => {:something => :invalid} + set.draw do + scope '/threads/:thread_id' do + resources :messages, :as => 'thread_messages' do + get :search, :on => :collection + match :preview, :on => :new + end end end - end - end - - def test_resource_action_separator - with_routing do |set| - set.draw do |map| - map.resources :messages, :collection => {:search => :get}, :new => {:preview => :any}, :name_prefix => 'thread_', :path_prefix => '/threads/:thread_id' - map.resource :account, :member => {:login => :get}, :new => {:preview => :any}, :name_prefix => 'admin_', :path_prefix => '/admin' - end - - action_separator = ActionController::Base.resource_action_separator assert_simply_restful_for :messages, :name_prefix => 'thread_', :path_prefix => 'threads/1/', :options => { :thread_id => '1' } - assert_named_route "/threads/1/messages#{action_separator}search", "search_thread_messages_path", {} - assert_named_route "/threads/1/messages/new", "new_thread_message_path", {} - assert_named_route "/threads/1/messages/new#{action_separator}preview", "preview_new_thread_message_path", {} - assert_singleton_restful_for :account, :name_prefix => 'admin_', :path_prefix => 'admin/' - assert_named_route "/admin/account#{action_separator}login", "login_admin_account_path", {} - assert_named_route "/admin/account/new", "new_admin_account_path", {} - assert_named_route "/admin/account/new#{action_separator}preview", "preview_new_admin_account_path", {} - end - end - - def test_new_style_named_routes_for_resource - with_routing do |set| - set.draw do |map| - map.resources :messages, :collection => {:search => :get}, :new => {:preview => :any}, :name_prefix => 'thread_', :path_prefix => '/threads/:thread_id' - end - assert_simply_restful_for :messages, :name_prefix => 'thread_', :path_prefix => 'threads/1/', :options => { :thread_id => '1' } assert_named_route "/threads/1/messages/search", "search_thread_messages_path", {} assert_named_route "/threads/1/messages/new", "new_thread_message_path", {} assert_named_route "/threads/1/messages/new/preview", "preview_new_thread_message_path", {} @@ -745,8 +678,13 @@ class ResourcesTest < ActionController::TestCase def test_new_style_named_routes_for_singleton_resource with_routing do |set| - set.draw do |map| - map.resource :account, :member => {:login => :get}, :new => {:preview => :any}, :name_prefix => 'admin_', :path_prefix => '/admin' + set.draw do + scope '/admin' do + resource :account, :as => :admin_account do + get :login, :on => :member + match :preview, :on => :new + end + end end assert_singleton_restful_for :account, :name_prefix => 'admin_', :path_prefix => 'admin/' assert_named_route "/admin/account/login", "login_admin_account_path", {} @@ -757,48 +695,22 @@ class ResourcesTest < ActionController::TestCase def test_resources_in_namespace with_routing do |set| - set.draw do |map| - map.namespace :backoffice do |backoffice| - backoffice.resources :products - end - end - - assert_simply_restful_for :products, :controller => "backoffice/products", :name_prefix => 'backoffice_', :path_prefix => 'backoffice/' - end - end - - def test_resource_has_many_in_namespace - with_routing do |set| - set.draw do |map| - map.namespace :backoffice do |backoffice| - backoffice.resources :products, :has_many => :tags - end - end - - assert_simply_restful_for :products, :controller => "backoffice/products", :name_prefix => 'backoffice_', :path_prefix => 'backoffice/' - assert_simply_restful_for :tags, :controller => "backoffice/tags", :name_prefix => "backoffice_product_", :path_prefix => 'backoffice/products/1/', :options => { :product_id => '1' } - end - end - - def test_resource_has_one_in_namespace - with_routing do |set| - set.draw do |map| - map.namespace :backoffice do |backoffice| - backoffice.resources :products, :has_one => :manufacturer + set.draw do + namespace :backoffice do + resources :products end end assert_simply_restful_for :products, :controller => "backoffice/products", :name_prefix => 'backoffice_', :path_prefix => 'backoffice/' - assert_singleton_restful_for :manufacturer, :controller => "backoffice/manufacturers", :name_prefix => 'backoffice_product_', :path_prefix => 'backoffice/products/1/', :options => { :product_id => '1' } end end def test_resources_in_nested_namespace with_routing do |set| - set.draw do |map| - map.namespace :backoffice do |backoffice| - backoffice.namespace :admin do |admin| - admin.resources :products + set.draw do + namespace :backoffice do + namespace :admin do + resources :products end end end @@ -809,8 +721,10 @@ class ResourcesTest < ActionController::TestCase def test_resources_using_namespace with_routing do |set| - set.draw do |map| - map.resources :products, :namespace => "backoffice/" + set.draw do + namespace :backoffice, :path => nil, :as => nil do + resources :products + end end assert_simply_restful_for :products, :controller => "backoffice/products" @@ -819,10 +733,10 @@ class ResourcesTest < ActionController::TestCase def test_nested_resources_using_namespace with_routing do |set| - set.draw do |map| - map.namespace :backoffice do |backoffice| - backoffice.resources :products do |products| - products.resources :images + set.draw do + namespace :backoffice do + resources :products do + resources :images end end end @@ -833,11 +747,11 @@ class ResourcesTest < ActionController::TestCase def test_nested_resources_in_nested_namespace with_routing do |set| - set.draw do |map| - map.namespace :backoffice do |backoffice| - backoffice.namespace :admin do |admin| - admin.resources :products do |products| - products.resources :images + set.draw do + namespace :backoffice do + namespace :admin do + resources :products do + resources :images end end end @@ -854,21 +768,24 @@ class ResourcesTest < ActionController::TestCase assert_recognizes({:controller => "messages", :action => "index"}, "/messages/") end - with_restful_routing :messages, :as => 'reviews' do - assert_simply_restful_for :messages, :as => 'reviews' - assert_recognizes({:controller => "messages", :action => "index"}, "/reviews") - assert_recognizes({:controller => "messages", :action => "index"}, "/reviews/") + with_routing do |set| + set.draw do + resources :messages, :path => 'reviews' + end + assert_simply_restful_for :messages, :as => 'reviews' + assert_recognizes({:controller => "messages", :action => "index"}, "/reviews") + assert_recognizes({:controller => "messages", :action => "index"}, "/reviews/") end end def test_multiple_with_path_segment_and_controller with_routing do |set| - set.draw do |map| - map.resources :products do |products| - products.resources :product_reviews, :as => 'reviews', :controller => 'messages' + set.draw do + resources :products do + resources :product_reviews, :path => 'reviews', :controller => 'messages' end - map.resources :tutors do |tutors| - tutors.resources :tutor_reviews, :as => 'reviews', :controller => 'comments' + resources :tutors do + resources :tutor_reviews, :path => 'reviews', :controller => 'comments' end end @@ -877,17 +794,22 @@ class ResourcesTest < ActionController::TestCase end end - def test_with_path_segment_path_prefix_requirements + def test_with_path_segment_path_prefix_constraints expected_options = {:controller => 'messages', :action => 'show', :thread_id => '1.1.1', :id => '1'} - with_restful_routing :messages, :as => 'comments',:path_prefix => '/thread/:thread_id', :requirements => { :thread_id => /[0-9]\.[0-9]\.[0-9]/ } do + with_routing do |set| + set.draw do + scope '/thread/:thread_id', :constraints => { :thread_id => /[0-9]\.[0-9]\.[0-9]/ } do + resources :messages, :path => 'comments' + end + end assert_recognizes(expected_options, :path => 'thread/1.1.1/comments/1', :method => :get) end end def test_resource_has_only_show_action with_routing do |set| - set.draw do |map| - map.resources :products, :only => :show + set.draw do + resources :products, :only => :show end assert_resource_allowed_routes('products', {}, { :id => '1' }, :show, [:index, :new, :create, :edit, :update, :destroy]) @@ -897,8 +819,8 @@ class ResourcesTest < ActionController::TestCase def test_singleton_resource_has_only_show_action with_routing do |set| - set.draw do |map| - map.resource :account, :only => :show + set.draw do + resource :account, :only => :show end assert_singleton_resource_allowed_routes('accounts', {}, :show, [:index, :new, :create, :edit, :update, :destroy]) @@ -908,8 +830,8 @@ class ResourcesTest < ActionController::TestCase def test_resource_does_not_have_destroy_action with_routing do |set| - set.draw do |map| - map.resources :products, :except => :destroy + set.draw do + resources :products, :except => :destroy end assert_resource_allowed_routes('products', {}, { :id => '1' }, [:index, :new, :create, :show, :edit, :update], :destroy) @@ -919,8 +841,8 @@ class ResourcesTest < ActionController::TestCase def test_singleton_resource_does_not_have_destroy_action with_routing do |set| - set.draw do |map| - map.resource :account, :except => :destroy + set.draw do + resource :account, :except => :destroy end assert_singleton_resource_allowed_routes('accounts', {}, [:new, :create, :show, :edit, :update], :destroy) @@ -930,8 +852,8 @@ class ResourcesTest < ActionController::TestCase def test_resource_has_only_create_action_and_named_route with_routing do |set| - set.draw do |map| - map.resources :products, :only => :create + set.draw do + resources :products, :only => :create end assert_resource_allowed_routes('products', {}, { :id => '1' }, :create, [:index, :new, :show, :edit, :update, :destroy]) @@ -943,8 +865,8 @@ class ResourcesTest < ActionController::TestCase def test_resource_has_only_update_action_and_named_route with_routing do |set| - set.draw do |map| - map.resources :products, :only => :update + set.draw do + resources :products, :only => :update end assert_resource_allowed_routes('products', {}, { :id => '1' }, :update, [:index, :new, :create, :show, :edit, :destroy]) @@ -956,8 +878,8 @@ class ResourcesTest < ActionController::TestCase def test_resource_has_only_destroy_action_and_named_route with_routing do |set| - set.draw do |map| - map.resources :products, :only => :destroy + set.draw do + resources :products, :only => :destroy end assert_resource_allowed_routes('products', {}, { :id => '1' }, :destroy, [:index, :new, :create, :show, :edit, :update]) @@ -969,8 +891,8 @@ class ResourcesTest < ActionController::TestCase def test_singleton_resource_has_only_create_action_and_named_route with_routing do |set| - set.draw do |map| - map.resource :account, :only => :create + set.draw do + resource :account, :only => :create end assert_singleton_resource_allowed_routes('accounts', {}, :create, [:new, :show, :edit, :update, :destroy]) @@ -982,8 +904,8 @@ class ResourcesTest < ActionController::TestCase def test_singleton_resource_has_only_update_action_and_named_route with_routing do |set| - set.draw do |map| - map.resource :account, :only => :update + set.draw do + resource :account, :only => :update end assert_singleton_resource_allowed_routes('accounts', {}, :update, [:new, :create, :show, :edit, :destroy]) @@ -995,8 +917,8 @@ class ResourcesTest < ActionController::TestCase def test_singleton_resource_has_only_destroy_action_and_named_route with_routing do |set| - set.draw do |map| - map.resource :account, :only => :destroy + set.draw do + resource :account, :only => :destroy end assert_singleton_resource_allowed_routes('accounts', {}, :destroy, [:new, :create, :show, :edit, :update]) @@ -1008,8 +930,10 @@ class ResourcesTest < ActionController::TestCase def test_resource_has_only_collection_action with_routing do |set| - set.draw do |map| - map.resources :products, :except => :all, :collection => { :sale => :get } + set.draw do + resources :products, :only => [] do + get :sale, :on => :collection + end end assert_resource_allowed_routes('products', {}, { :id => '1' }, [], [:index, :new, :create, :show, :edit, :update, :destroy]) @@ -1022,8 +946,10 @@ class ResourcesTest < ActionController::TestCase def test_resource_has_only_member_action with_routing do |set| - set.draw do |map| - map.resources :products, :except => :all, :member => { :preview => :get } + set.draw do + resources :products, :only => [] do + get :preview, :on => :member + end end assert_resource_allowed_routes('products', {}, { :id => '1' }, [], [:index, :new, :create, :show, :edit, :update, :destroy]) @@ -1036,8 +962,12 @@ class ResourcesTest < ActionController::TestCase def test_singleton_resource_has_only_member_action with_routing do |set| - set.draw do |map| - map.resource :account, :except => :all, :member => { :signup => :get } + set.draw do + resource :account, :only => [] do + member do + get :signup + end + end end assert_singleton_resource_allowed_routes('accounts', {}, [], [:new, :create, :show, :edit, :update, :destroy]) @@ -1050,9 +980,11 @@ class ResourcesTest < ActionController::TestCase def test_nested_resource_has_only_show_and_member_action with_routing do |set| - set.draw do |map| - map.resources :products, :only => [:index, :show] do |product| - product.resources :images, :member => { :thumbnail => :get }, :only => :show + set.draw do + resources :products, :only => [:index, :show] do + resources :images, :only => :show do + get :thumbnail, :on => :member + end end end @@ -1066,9 +998,9 @@ class ResourcesTest < ActionController::TestCase def test_nested_resource_does_not_inherit_only_option with_routing do |set| - set.draw do |map| - map.resources :products, :only => :show do |product| - product.resources :images, :except => :destroy + set.draw do + resources :products, :only => :show do + resources :images, :except => :destroy end end @@ -1079,9 +1011,9 @@ class ResourcesTest < ActionController::TestCase def test_nested_resource_does_not_inherit_only_option_by_default with_routing do |set| - set.draw do |map| - map.resources :products, :only => :show do |product| - product.resources :images + set.draw do + resources :products, :only => :show do + resources :images end end @@ -1092,9 +1024,9 @@ class ResourcesTest < ActionController::TestCase def test_nested_resource_does_not_inherit_except_option with_routing do |set| - set.draw do |map| - map.resources :products, :except => :show do |product| - product.resources :images, :only => :destroy + set.draw do + resources :products, :except => :show do + resources :images, :only => :destroy end end @@ -1105,9 +1037,9 @@ class ResourcesTest < ActionController::TestCase def test_nested_resource_does_not_inherit_except_option_by_default with_routing do |set| - set.draw do |map| - map.resources :products, :except => :show do |product| - product.resources :images + set.draw do + resources :products, :except => :show do + resources :images end end @@ -1118,8 +1050,8 @@ class ResourcesTest < ActionController::TestCase def test_default_singleton_restful_route_uses_get with_routing do |set| - set.draw do |map| - map.resource :product + set.draw do + resource :product end assert_routing '/product', :controller => 'products', :action => 'show' @@ -1135,15 +1067,41 @@ class ResourcesTest < ActionController::TestCase protected def with_restful_routing(*args) + options = args.extract_options! + collection_methods = options.delete(:collection) + member_methods = options.delete(:member) + path_prefix = options.delete(:path_prefix) + args.push(options) + with_routing do |set| - set.draw { |map| map.resources(*args) } + set.draw do + scope(path_prefix || '') do + resources(*args) do + if collection_methods + collection do + collection_methods.each do |name, method| + send(method, name) + end + end + end + + if member_methods + member do + member_methods.each do |name, method| + send(method, name) + end + end + end + end + end + end yield end end def with_singleton_resources(*args) with_routing do |set| - set.draw { |map| map.resource(*args) } + set.draw {resource(*args) } yield end end @@ -1385,7 +1343,7 @@ class ResourcesTest < ActionController::TestCase end def distinct_routes? (r1, r2) - if r1.conditions == r2.conditions and r1.requirements == r2.requirements then + if r1.conditions == r2.conditions and r1.constraints == r2.constraints then if r1.segments.collect(&:to_s) == r2.segments.collect(&:to_s) then return false end diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb index fc85b01394..18cf944f46 100644 --- a/actionpack/test/controller/routing_test.rb +++ b/actionpack/test/controller/routing_test.rb @@ -2,6 +2,7 @@ require 'abstract_unit' require 'controller/fake_controllers' require 'active_support/dependencies' +require 'active_support/core_ext/object/with_options' class MilestonesController < ActionController::Base def index() head :ok end @@ -9,14 +10,22 @@ class MilestonesController < ActionController::Base def rescue_action(e) raise e end end -ROUTING = ActionController::Routing +ROUTING = ActionDispatch::Routing + +module RoutingTestHelpers + def url_for(set, options, recall = nil) + set.send(:url_for, options.merge(:only_path => true, :_path_segments => recall)) + end +end # See RFC 3986, section 3.3 for allowed path characters. class UriReservedCharactersRoutingTest < Test::Unit::TestCase + include RoutingTestHelpers + def setup - @set = ActionController::Routing::RouteSet.new - @set.draw do |map| - map.connect ':controller/:action/:variable/*additional' + @set = ActionDispatch::Routing::RouteSet.new + @set.draw do + match ':controller/:action/:variable/*additional' end safe, unsafe = %w(: @ & = + $ , ;), %w(^ ? # [ ]) @@ -27,27 +36,31 @@ class UriReservedCharactersRoutingTest < Test::Unit::TestCase end def test_route_generation_escapes_unsafe_path_characters - @set.generate(:controller => "content", :action => "act#{@segment}ion", :variable => "variable", :additional => "foo") assert_equal "/content/act#{@escaped}ion/var#{@escaped}iable/add#{@escaped}itional-1/add#{@escaped}itional-2", - @set.generate(:controller => "content", - :action => "act#{@segment}ion", - :variable => "var#{@segment}iable", - :additional => ["add#{@segment}itional-1", "add#{@segment}itional-2"]) + url_for(@set, { + :controller => "content", + :action => "act#{@segment}ion", + :variable => "var#{@segment}iable", + :additional => ["add#{@segment}itional-1", "add#{@segment}itional-2"] + }) end def test_route_recognition_unescapes_path_components options = { :controller => "content", :action => "act#{@segment}ion", :variable => "var#{@segment}iable", - :additional => ["add#{@segment}itional-1", "add#{@segment}itional-2"] } + :additional => "add#{@segment}itional-1/add#{@segment}itional-2" } assert_equal options, @set.recognize_path("/content/act#{@escaped}ion/var#{@escaped}iable/add#{@escaped}itional-1/add#{@escaped}itional-2") end def test_route_generation_allows_passing_non_string_values_to_generated_helper - assert_equal "/content/action/variable/1/2", @set.generate(:controller => "content", - :action => "action", - :variable => "variable", - :additional => [1, 2]) + assert_equal "/content/action/variable/1/2", + url_for(@set, { + :controller => "content", + :action => "action", + :variable => "variable", + :additional => [1, 2] + }) end end @@ -67,10 +80,12 @@ class MockController end class LegacyRouteSetTests < Test::Unit::TestCase + include RoutingTestHelpers + attr_reader :rs def setup - @rs = ::ActionController::Routing::RouteSet.new + @rs = ::ActionDispatch::Routing::RouteSet.new end def teardown @@ -78,80 +93,83 @@ class LegacyRouteSetTests < Test::Unit::TestCase end def test_default_setup - @rs.draw {|m| m.connect ':controller/:action/:id' } + @rs.draw { match '/:controller(/:action(/:id))' } assert_equal({:controller => "content", :action => 'index'}, rs.recognize_path("/content")) - assert_equal({:controller => "content", :action => 'list'}, rs.recognize_path("/content/list")) + assert_equal({:controller => "content", :action => 'list'}, rs.recognize_path("/content/list")) assert_equal({:controller => "content", :action => 'show', :id => '10'}, rs.recognize_path("/content/show/10")) assert_equal({:controller => "admin/user", :action => 'show', :id => '10'}, rs.recognize_path("/admin/user/show/10")) - assert_equal '/admin/user/show/10', rs.generate(:controller => 'admin/user', :action => 'show', :id => 10) + assert_equal '/admin/user/show/10', url_for(rs, { :controller => 'admin/user', :action => 'show', :id => 10 }) - assert_equal '/admin/user/show', rs.generate({:action => 'show'}, {:controller => 'admin/user', :action => 'list', :id => '10'}) - assert_equal '/admin/user/list/10', rs.generate({}, {:controller => 'admin/user', :action => 'list', :id => '10'}) + assert_equal '/admin/user/show', url_for(rs, { :action => 'show' }, { :controller => 'admin/user', :action => 'list', :id => '10' }) + assert_equal '/admin/user/list/10', url_for(rs, {}, { :controller => 'admin/user', :action => 'list', :id => '10' }) - assert_equal '/admin/stuff', rs.generate({:controller => 'stuff'}, {:controller => 'admin/user', :action => 'list', :id => '10'}) - assert_equal '/stuff', rs.generate({:controller => '/stuff'}, {:controller => 'admin/user', :action => 'list', :id => '10'}) + assert_equal '/admin/stuff', url_for(rs, { :controller => 'stuff' }, { :controller => 'admin/user', :action => 'list', :id => '10' }) + assert_equal '/stuff', url_for(rs, { :controller => '/stuff' }, { :controller => 'admin/user', :action => 'list', :id => '10' }) end def test_ignores_leading_slash @rs.clear! - @rs.draw {|m| m.connect '/:controller/:action/:id'} + @rs.draw { match '/:controller(/:action(/:id))'} test_default_setup end def test_time_recognition # We create many routes to make situation more realistic - @rs = ::ActionController::Routing::RouteSet.new - @rs.draw { |map| - map.frontpage '', :controller => 'search', :action => 'new' - map.resources :videos do |video| - video.resources :comments - video.resource :file, :controller => 'video_file' - video.resource :share, :controller => 'video_shares' - video.resource :abuse, :controller => 'video_abuses' + @rs = ::ActionDispatch::Routing::RouteSet.new + @rs.draw { + root :to => "search#new", :as => "frontpage" + resources :videos do + resources :comments + resource :file, :controller => 'video_file' + resource :share, :controller => 'video_shares' + resource :abuse, :controller => 'video_abuses' end - map.resources :abuses, :controller => 'video_abuses' - map.resources :video_uploads - map.resources :video_visits + resources :abuses, :controller => 'video_abuses' + resources :video_uploads + resources :video_visits - map.resources :users do |user| - user.resource :settings - user.resources :videos + resources :users do + resource :settings + resources :videos end - map.resources :channels do |channel| - channel.resources :videos, :controller => 'channel_videos' + resources :channels do + resources :videos, :controller => 'channel_videos' end - map.resource :session - map.resource :lost_password - map.search 'search', :controller => 'search' - map.resources :pages - map.connect ':controller/:action/:id' + resource :session + resource :lost_password + match 'search' => 'search#index', :as => 'search' + resources :pages + match ':controller/:action/:id' } end def test_route_with_colon_first - rs.draw do |map| - map.connect '/:controller/:action/:id', :action => 'index', :id => nil - map.connect ':url', :controller => 'tiny_url', :action => 'translate' + rs.draw do + match '/:controller/:action/:id', :action => 'index', :id => nil + match ':url', :controller => 'tiny_url', :action => 'translate' end end def test_route_with_regexp_for_controller - rs.draw do |map| - map.connect ':controller/:admintoken/:action/:id', :controller => /admin\/.+/ - map.connect ':controller/:action/:id' + rs.draw do + match ':controller/:admintoken(/:action(/:id))', :controller => /admin\/.+/ + match '/:controller(/:action(/:id))' end + assert_equal({:controller => "admin/user", :admintoken => "foo", :action => "index"}, rs.recognize_path("/admin/user/foo")) - assert_equal({:controller => "content", :action => "foo"}, rs.recognize_path("/content/foo")) - assert_equal '/admin/user/foo', rs.generate(:controller => "admin/user", :admintoken => "foo", :action => "index") - assert_equal '/content/foo', rs.generate(:controller => "content", :action => "foo") + assert_equal({:controller => "content", :action => "foo"}, + rs.recognize_path("/content/foo")) + + assert_equal '/admin/user/foo', url_for(rs, { :controller => "admin/user", :admintoken => "foo", :action => "index" }) + assert_equal '/content/foo', url_for(rs, { :controller => "content", :action => "foo" }) end def test_route_with_regexp_and_captures_for_controller - rs.draw do |map| - map.connect ':controller/:action/:id', :controller => /admin\/(accounts|users)/ + rs.draw do + match '/:controller(/:action(/:id))', :controller => /admin\/(accounts|users)/ end assert_equal({:controller => "admin/accounts", :action => "index"}, rs.recognize_path("/admin/accounts")) assert_equal({:controller => "admin/users", :action => "index"}, rs.recognize_path("/admin/users")) @@ -159,100 +177,97 @@ class LegacyRouteSetTests < Test::Unit::TestCase end def test_route_with_regexp_and_dot - rs.draw do |map| - map.connect ':controller/:action/:file', - :controller => /admin|user/, - :action => /upload|download/, - :defaults => {:file => nil}, - :requirements => {:file => %r{[^/]+(\.[^/]+)?}} + rs.draw do + match ':controller/:action/:file', + :controller => /admin|user/, + :action => /upload|download/, + :defaults => {:file => nil}, + :constraints => {:file => %r{[^/]+(\.[^/]+)?}} end # Without a file extension assert_equal '/user/download/file', - rs.generate(:controller => "user", :action => "download", :file => "file") - assert_equal( - {:controller => "user", :action => "download", :file => "file"}, + url_for(rs, { :controller => "user", :action => "download", :file => "file" }) + + assert_equal({:controller => "user", :action => "download", :file => "file"}, rs.recognize_path("/user/download/file")) # Now, let's try a file with an extension, really a dot (.) assert_equal '/user/download/file.jpg', - rs.generate( - :controller => "user", :action => "download", :file => "file.jpg") - assert_equal( - {:controller => "user", :action => "download", :file => "file.jpg"}, + url_for(rs, { :controller => "user", :action => "download", :file => "file.jpg" }) + + assert_equal({:controller => "user", :action => "download", :file => "file.jpg"}, rs.recognize_path("/user/download/file.jpg")) end def test_basic_named_route - rs.draw do |map| - map.home '', :controller => 'content', :action => 'list' + rs.draw do + root :to => 'content#list', :as => 'home' end - x = setup_for_named_route - assert_equal("http://test.host/", - x.send(:home_url)) + assert_equal("http://test.host/", setup_for_named_route.send(:home_url)) end def test_named_route_with_option - rs.draw do |map| - map.page 'page/:title', :controller => 'content', :action => 'show_page' + rs.draw do + match 'page/:title' => 'content#show_page', :as => 'page' end - x = setup_for_named_route + assert_equal("http://test.host/page/new%20stuff", - x.send(:page_url, :title => 'new stuff')) + setup_for_named_route.send(:page_url, :title => 'new stuff')) end def test_named_route_with_default - rs.draw do |map| - map.page 'page/:title', :controller => 'content', :action => 'show_page', :title => 'AboutPage' + rs.draw do + match 'page/:title' => 'content#show_page', :title => 'AboutPage', :as => 'page' end - x = setup_for_named_route - assert_equal("http://test.host/page/AboutRails", - x.send(:page_url, :title => "AboutRails")) - end - - def test_named_route_with_name_prefix - rs.draw do |map| - map.page 'page', :controller => 'content', :action => 'show_page', :name_prefix => 'my_' - end - x = setup_for_named_route - assert_equal("http://test.host/page", - x.send(:my_page_url)) + assert_equal("http://test.host/page/AboutRails", + setup_for_named_route.send(:page_url, :title => "AboutRails")) end def test_named_route_with_path_prefix - rs.draw do |map| - map.page 'page', :controller => 'content', :action => 'show_page', :path_prefix => 'my' + rs.draw do + scope "my" do + match 'page' => 'content#show_page', :as => 'page' + end end - x = setup_for_named_route + assert_equal("http://test.host/my/page", - x.send(:page_url)) + setup_for_named_route.send(:page_url)) end def test_named_route_with_blank_path_prefix - rs.draw do |map| - map.page 'page', :controller => 'content', :action => 'show_page', :path_prefix => '' + rs.draw do + scope "" do + match 'page' => 'content#show_page', :as => 'page' + end end - x = setup_for_named_route + assert_equal("http://test.host/page", - x.send(:page_url)) + setup_for_named_route.send(:page_url)) end def test_named_route_with_nested_controller - rs.draw do |map| - map.users 'admin/user', :controller => 'admin/user', :action => 'index' + rs.draw do + match 'admin/user' => 'admin/user#index', :as => "users" end - x = setup_for_named_route + assert_equal("http://test.host/admin/user", - x.send(:users_url)) + setup_for_named_route.send(:users_url)) end def test_optimised_named_route_with_host - rs.draw do |map| - map.pages 'pages', :controller => 'content', :action => 'show_page', :host => 'foo.com' + rs.draw do + match 'page' => 'content#show_page', :as => 'pages', :host => 'foo.com' end - x = setup_for_named_route - x.expects(:url_for).with(:host => 'foo.com', :only_path => false, :controller => 'content', :action => 'show_page', :use_route => :pages).once - x.send(:pages_url) + routes = setup_for_named_route + routes.expects(:url_for).with({ + :host => 'foo.com', + :only_path => false, + :controller => 'content', + :action => 'show_page', + :use_route => 'pages' + }).once + routes.send(:pages_url) end def setup_for_named_route @@ -260,263 +275,229 @@ class LegacyRouteSetTests < Test::Unit::TestCase end def test_named_route_without_hash - rs.draw do |map| - map.normal ':controller/:action/:id' + rs.draw do + match ':controller/:action/:id', :as => 'normal' end end def test_named_route_root - rs.draw do |map| - map.root :controller => "hello" + rs.draw do + root :to => "hello#index" end - x = setup_for_named_route - assert_equal("http://test.host/", x.send(:root_url)) - assert_equal("/", x.send(:root_path)) + routes = setup_for_named_route + assert_equal("http://test.host/", routes.send(:root_url)) + assert_equal("/", routes.send(:root_path)) end def test_named_route_with_regexps - rs.draw do |map| - map.article 'page/:year/:month/:day/:title', :controller => 'page', :action => 'show', + rs.draw do + match 'page/:year/:month/:day/:title' => 'page#show', :as => 'article', :year => /\d+/, :month => /\d+/, :day => /\d+/ - map.connect ':controller/:action/:id' + match ':controller/:action/:id' end - x = setup_for_named_route - # assert_equal( - # {:controller => 'page', :action => 'show', :title => 'hi', :use_route => :article, :only_path => false}, - # x.send(:article_url, :title => 'hi') - # ) - assert_equal( - "http://test.host/page/2005/6/10/hi", - x.send(:article_url, :title => 'hi', :day => 10, :year => 2005, :month => 6) - ) + + routes = setup_for_named_route + + assert_equal "http://test.host/page/2005/6/10/hi", + routes.send(:article_url, :title => 'hi', :day => 10, :year => 2005, :month => 6) end def test_changing_controller - @rs.draw {|m| m.connect ':controller/:action/:id' } + @rs.draw { match ':controller/:action/:id' } - assert_equal '/admin/stuff/show/10', rs.generate( - {:controller => 'stuff', :action => 'show', :id => 10}, - {:controller => 'admin/user', :action => 'index'} - ) + assert_equal '/admin/stuff/show/10', + url_for(rs, {:controller => 'stuff', :action => 'show', :id => 10}, + {:controller => 'admin/user', :action => 'index'}) end def test_paths_escaped - rs.draw do |map| - map.path 'file/*path', :controller => 'content', :action => 'show_file' - map.connect ':controller/:action/:id' + rs.draw do + match 'file/*path' => 'content#show_file', :as => 'path' + match ':controller/:action/:id' end # No + to space in URI escaping, only for query params. results = rs.recognize_path "/file/hello+world/how+are+you%3F" assert results, "Recognition should have succeeded" - assert_equal ['hello+world', 'how+are+you?'], results[:path] + assert_equal 'hello+world/how+are+you?', results[:path] # Use %20 for space instead. results = rs.recognize_path "/file/hello%20world/how%20are%20you%3F" assert results, "Recognition should have succeeded" - assert_equal ['hello world', 'how are you?'], results[:path] + assert_equal 'hello world/how are you?', results[:path] end def test_paths_slashes_unescaped_with_ordered_parameters - rs.draw do |map| - map.path '/file/*path', :controller => 'content' + rs.draw do + match '/file/*path' => 'content#index', :as => 'path' end # No / to %2F in URI, only for query params. - x = setup_for_named_route - assert_equal("/file/hello/world", x.send(:path_path, ['hello', 'world'])) + assert_equal("/file/hello/world", setup_for_named_route.send(:path_path, ['hello', 'world'])) end def test_non_controllers_cannot_be_matched - rs.draw do |map| - map.connect ':controller/:action/:id' + rs.draw do + match ':controller/:action/:id' end assert_raise(ActionController::RoutingError) { rs.recognize_path("/not_a/show/10") } end - def test_paths_do_not_accept_defaults - assert_raise(ActionController::RoutingError) do - rs.draw do |map| - map.path 'file/*path', :controller => 'content', :action => 'show_file', :path => %w(fake default) - map.connect ':controller/:action/:id' - end - end - - rs.draw do |map| - map.path 'file/*path', :controller => 'content', :action => 'show_file', :path => [] - map.connect ':controller/:action/:id' + def test_should_list_options_diff_when_routing_constraints_dont_match + rs.draw do + match 'post/:id' => 'post#show', :constraints => { :id => /\d+/ }, :as => 'post' end - end - - def test_should_list_options_diff_when_routing_requirements_dont_match - rs.draw do |map| - map.post 'post/:id', :controller=> 'post', :action=> 'show', :requirements => {:id => /\d+/} + assert_raise(ActionController::RoutingError) do + url_for(rs, { :controller => 'post', :action => 'show', :bad_param => "foo", :use_route => "post" }) end - assert_raise(ActionController::RoutingError) { rs.generate(:controller => 'post', :action => 'show', :bad_param => "foo", :use_route => "post") } end def test_dynamic_path_allowed - rs.draw do |map| - map.connect '*path', :controller => 'content', :action => 'show_file' + rs.draw do + match '*path' => 'content#show_file' end - assert_equal '/pages/boo', rs.generate(:controller => 'content', :action => 'show_file', :path => %w(pages boo)) + assert_equal '/pages/boo', + url_for(rs, { :controller => 'content', :action => 'show_file', :path => %w(pages boo) }) end def test_dynamic_recall_paths_allowed - rs.draw do |map| - map.connect '*path', :controller => 'content', :action => 'show_file' + rs.draw do + match '*path' => 'content#show_file' end - assert_equal '/pages/boo', rs.generate({}, :controller => 'content', :action => 'show_file', :path => %w(pages boo)) + assert_equal '/pages/boo', + url_for(rs, {}, { :controller => 'content', :action => 'show_file', :path => %w(pages boo) }) end def test_backwards - rs.draw do |map| - map.connect 'page/:id/:action', :controller => 'pages', :action => 'show' - map.connect ':controller/:action/:id' + rs.draw do + match 'page/:id(/:action)' => 'pages#show' + match ':controller(/:action(/:id))' end - assert_equal '/page/20', rs.generate({:id => 20}, {:controller => 'pages', :action => 'show'}) - assert_equal '/page/20', rs.generate(:controller => 'pages', :id => 20, :action => 'show') - assert_equal '/pages/boo', rs.generate(:controller => 'pages', :action => 'boo') + assert_equal '/page/20', url_for(rs, { :id => 20 }, { :controller => 'pages', :action => 'show' }) + assert_equal '/page/20', url_for(rs, { :controller => 'pages', :id => 20, :action => 'show' }) + assert_equal '/pages/boo', url_for(rs, { :controller => 'pages', :action => 'boo' }) end def test_route_with_fixnum_default - rs.draw do |map| - map.connect 'page/:id', :controller => 'content', :action => 'show_page', :id => 1 - map.connect ':controller/:action/:id' + rs.draw do + match 'page(/:id)' => 'content#show_page', :id => 1 + match ':controller/:action/:id' end - assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page') - assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page', :id => 1) - assert_equal '/page', rs.generate(:controller => 'content', :action => 'show_page', :id => '1') - assert_equal '/page/10', rs.generate(:controller => 'content', :action => 'show_page', :id => 10) + assert_equal '/page', url_for(rs, { :controller => 'content', :action => 'show_page' }) + assert_equal '/page', url_for(rs, { :controller => 'content', :action => 'show_page', :id => 1 }) + assert_equal '/page', url_for(rs, { :controller => 'content', :action => 'show_page', :id => '1' }) + assert_equal '/page/10', url_for(rs, { :controller => 'content', :action => 'show_page', :id => 10 }) - assert_equal({:controller => "content", :action => 'show_page', :id => '1'}, rs.recognize_path("/page")) + assert_equal({:controller => "content", :action => 'show_page', :id => 1 }, rs.recognize_path("/page")) assert_equal({:controller => "content", :action => 'show_page', :id => '1'}, rs.recognize_path("/page/1")) assert_equal({:controller => "content", :action => 'show_page', :id => '10'}, rs.recognize_path("/page/10")) end # For newer revision def test_route_with_text_default - rs.draw do |map| - map.connect 'page/:id', :controller => 'content', :action => 'show_page', :id => 1 - map.connect ':controller/:action/:id' + rs.draw do + match 'page/:id' => 'content#show_page', :id => 1 + match ':controller/:action/:id' end - assert_equal '/page/foo', rs.generate(:controller => 'content', :action => 'show_page', :id => 'foo') - assert_equal({:controller => "content", :action => 'show_page', :id => 'foo'}, rs.recognize_path("/page/foo")) + assert_equal '/page/foo', url_for(rs, { :controller => 'content', :action => 'show_page', :id => 'foo' }) + assert_equal({ :controller => "content", :action => 'show_page', :id => 'foo' }, rs.recognize_path("/page/foo")) - token = "\321\202\320\265\320\272\321\201\321\202" # 'text' in russian + token = "\321\202\320\265\320\272\321\201\321\202" # 'text' in Russian token.force_encoding(Encoding::BINARY) if token.respond_to?(:force_encoding) escaped_token = CGI::escape(token) - assert_equal '/page/' + escaped_token, rs.generate(:controller => 'content', :action => 'show_page', :id => token) - assert_equal({:controller => "content", :action => 'show_page', :id => token}, rs.recognize_path("/page/#{escaped_token}")) + assert_equal '/page/' + escaped_token, url_for(rs, { :controller => 'content', :action => 'show_page', :id => token }) + assert_equal({ :controller => "content", :action => 'show_page', :id => token }, rs.recognize_path("/page/#{escaped_token}")) end def test_action_expiry - @rs.draw {|m| m.connect ':controller/:action/:id' } - assert_equal '/content', rs.generate({:controller => 'content'}, {:controller => 'content', :action => 'show'}) + @rs.draw { match ':controller(/:action(/:id))' } + assert_equal '/content', url_for(rs, { :controller => 'content' }, { :controller => 'content', :action => 'show' }) end def test_requirement_should_prevent_optional_id - rs.draw do |map| - map.post 'post/:id', :controller=> 'post', :action=> 'show', :requirements => {:id => /\d+/} + rs.draw do + match 'post/:id' => 'post#show', :constraints => {:id => /\d+/}, :as => 'post' end - assert_equal '/post/10', rs.generate(:controller => 'post', :action => 'show', :id => 10) + assert_equal '/post/10', url_for(rs, { :controller => 'post', :action => 'show', :id => 10 }) assert_raise ActionController::RoutingError do - rs.generate(:controller => 'post', :action => 'show') + url_for(rs, { :controller => 'post', :action => 'show' }) end end def test_both_requirement_and_optional - rs.draw do |map| - map.blog('test/:year', :controller => 'post', :action => 'show', + rs.draw do + match('test(/:year)' => 'post#show', :as => 'blog', :defaults => { :year => nil }, - :requirements => { :year => /\d{4}/ } + :constraints => { :year => /\d{4}/ } ) - map.connect ':controller/:action/:id' + match ':controller/:action/:id' end - assert_equal '/test', rs.generate(:controller => 'post', :action => 'show') - assert_equal '/test', rs.generate(:controller => 'post', :action => 'show', :year => nil) + assert_equal '/test', url_for(rs, { :controller => 'post', :action => 'show' }) + assert_equal '/test', url_for(rs, { :controller => 'post', :action => 'show', :year => nil }) - x = setup_for_named_route - assert_equal("http://test.host/test", - x.send(:blog_url)) + assert_equal("http://test.host/test", setup_for_named_route.send(:blog_url)) end def test_set_to_nil_forgets - rs.draw do |map| - map.connect 'pages/:year/:month/:day', :controller => 'content', :action => 'list_pages', :month => nil, :day => nil - map.connect ':controller/:action/:id' + rs.draw do + match 'pages(/:year(/:month(/:day)))' => 'content#list_pages', :month => nil, :day => nil + match ':controller/:action/:id' end assert_equal '/pages/2005', - rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005) + url_for(rs, { :controller => 'content', :action => 'list_pages', :year => 2005 }) assert_equal '/pages/2005/6', - rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005, :month => 6) + url_for(rs, { :controller => 'content', :action => 'list_pages', :year => 2005, :month => 6 }) assert_equal '/pages/2005/6/12', - rs.generate(:controller => 'content', :action => 'list_pages', :year => 2005, :month => 6, :day => 12) + url_for(rs, { :controller => 'content', :action => 'list_pages', :year => 2005, :month => 6, :day => 12 }) assert_equal '/pages/2005/6/4', - rs.generate({:day => 4}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'}) + url_for(rs, { :day => 4 }, { :controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12' }) assert_equal '/pages/2005/6', - rs.generate({:day => nil}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'}) + url_for(rs, { :day => nil }, { :controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12' }) assert_equal '/pages/2005', - rs.generate({:day => nil, :month => nil}, {:controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12'}) + url_for(rs, { :day => nil, :month => nil }, { :controller => 'content', :action => 'list_pages', :year => '2005', :month => '6', :day => '12' }) end - def test_url_with_no_action_specified - rs.draw do |map| - map.connect '', :controller => 'content' - map.connect ':controller/:action/:id' + def test_root_url_generation_with_controller_and_action + rs.draw do + root :to => "content#index" end - assert_equal '/', rs.generate(:controller => 'content', :action => 'index') - assert_equal '/', rs.generate(:controller => 'content') + assert_equal '/', url_for(rs, { :controller => 'content', :action => 'index' }) + assert_equal '/', url_for(rs, { :controller => 'content' }) end - def test_named_url_with_no_action_specified - rs.draw do |map| - map.home '', :controller => 'content' - map.connect ':controller/:action/:id' + def test_named_root_url_generation_with_controller_and_action + rs.draw do + root :to => "content#index", :as => 'home' end - assert_equal '/', rs.generate(:controller => 'content', :action => 'index') - assert_equal '/', rs.generate(:controller => 'content') + assert_equal '/', url_for(rs, { :controller => 'content', :action => 'index' }) + assert_equal '/', url_for(rs, { :controller => 'content' }) - x = setup_for_named_route - assert_equal("http://test.host/", - x.send(:home_url)) - end - - def test_url_generated_when_forgetting_action - [{:controller => 'content', :action => 'index'}, {:controller => 'content'}].each do |hash| - rs.draw do |map| - map.home '', hash - map.connect ':controller/:action/:id' - end - assert_equal '/', rs.generate({:action => nil}, {:controller => 'content', :action => 'hello'}) - assert_equal '/', rs.generate({:controller => 'content'}) - assert_equal '/content/hi', rs.generate({:controller => 'content', :action => 'hi'}) - end + assert_equal("http://test.host/", setup_for_named_route.send(:home_url)) end def test_named_route_method - rs.draw do |map| - map.categories 'categories', :controller => 'content', :action => 'categories' - map.connect ':controller/:action/:id' + rs.draw do + match 'categories' => 'content#categories', :as => 'categories' + match ':controller(/:action(/:id))' end - assert_equal '/categories', rs.generate(:controller => 'content', :action => 'categories') - assert_equal '/content/hi', rs.generate({:controller => 'content', :action => 'hi'}) + assert_equal '/categories', url_for(rs, { :controller => 'content', :action => 'categories' }) + assert_equal '/content/hi', url_for(rs, { :controller => 'content', :action => 'hi' }) end def test_named_routes_array @@ -525,23 +506,26 @@ class LegacyRouteSetTests < Test::Unit::TestCase end def test_nil_defaults - rs.draw do |map| - map.connect 'journal', - :controller => 'content', - :action => 'list_journal', + rs.draw do + match 'journal' => 'content#list_journal', :date => nil, :user_id => nil - map.connect ':controller/:action/:id' + match ':controller/:action/:id' end - assert_equal '/journal', rs.generate(:controller => 'content', :action => 'list_journal', :date => nil, :user_id => nil) + assert_equal '/journal', url_for(rs, { + :controller => 'content', + :action => 'list_journal', + :date => nil, + :user_id => nil + }) end def setup_request_method_routes_for(method) - rs.draw do |r| - r.connect '/match', :controller => 'books', :action => 'get', :conditions => { :method => :get } - r.connect '/match', :controller => 'books', :action => 'post', :conditions => { :method => :post } - r.connect '/match', :controller => 'books', :action => 'put', :conditions => { :method => :put } - r.connect '/match', :controller => 'books', :action => 'delete', :conditions => { :method => :delete } + rs.draw do + match '/match' => 'books#get', :via => :get + match '/match' => 'books#post', :via => :post + match '/match' => 'books#put', :via => :put + match '/match' => 'books#delete', :via => :delete end end @@ -554,9 +538,9 @@ class LegacyRouteSetTests < Test::Unit::TestCase end def test_recognize_array_of_methods - rs.draw do |r| - r.connect '/match', :controller => 'books', :action => 'get_or_post', :conditions => { :method => [:get, :post] } - r.connect '/match', :controller => 'books', :action => 'not_get_or_post' + rs.draw do + match '/match' => 'books#get_or_post', :via => [:get, :post] + match '/match' => 'books#not_get_or_post' end params = rs.recognize_path("/match", :method => :post) @@ -567,11 +551,11 @@ class LegacyRouteSetTests < Test::Unit::TestCase end def test_subpath_recognized - rs.draw do |r| - r.connect '/books/:id/edit', :controller => 'subpath_books', :action => 'edit' - r.connect '/items/:id/:action', :controller => 'subpath_books' - r.connect '/posts/new/:action', :controller => 'subpath_books' - r.connect '/posts/:id', :controller => 'subpath_books', :action => "show" + rs.draw do + match '/books/:id/edit' => 'subpath_books#edit' + match '/items/:id/:action' => 'subpath_books' + match '/posts/new/:action' => 'subpath_books' + match '/posts/:id' => 'subpath_books#show' end hash = rs.recognize_path "/books/17/edit" @@ -592,36 +576,35 @@ class LegacyRouteSetTests < Test::Unit::TestCase end def test_subpath_generated - rs.draw do |r| - r.connect '/books/:id/edit', :controller => 'subpath_books', :action => 'edit' - r.connect '/items/:id/:action', :controller => 'subpath_books' - r.connect '/posts/new/:action', :controller => 'subpath_books' + rs.draw do + match '/books/:id/edit' => 'subpath_books#edit' + match '/items/:id/:action' => 'subpath_books' + match '/posts/new/:action' => 'subpath_books' end - assert_equal "/books/7/edit", rs.generate(:controller => "subpath_books", :id => 7, :action => "edit") - assert_equal "/items/15/complete", rs.generate(:controller => "subpath_books", :id => 15, :action => "complete") - assert_equal "/posts/new/preview", rs.generate(:controller => "subpath_books", :action => "preview") + assert_equal "/books/7/edit", url_for(rs, { :controller => "subpath_books", :id => 7, :action => "edit" }) + assert_equal "/items/15/complete", url_for(rs, { :controller => "subpath_books", :id => 15, :action => "complete" }) + assert_equal "/posts/new/preview", url_for(rs, { :controller => "subpath_books", :action => "preview" }) end - def test_failed_requirements_raises_exception_with_violated_requirements - rs.draw do |r| - r.foo_with_requirement 'foos/:id', :controller=>'foos', :requirements=>{:id=>/\d+/} + def test_failed_constraints_raises_exception_with_violated_constraints + rs.draw do + match 'foos/:id' => 'foos#show', :as => 'foo_with_requirement', :constraints => { :id => /\d+/ } end - x = setup_for_named_route assert_raise(ActionController::RoutingError) do - x.send(:foo_with_requirement_url, "I am Against the requirements") + setup_for_named_route.send(:foo_with_requirement_url, "I am Against the constraints") end end def test_routes_changed_correctly_after_clear - rs = ::ActionController::Routing::RouteSet.new - rs.draw do |r| - r.connect 'ca', :controller => 'ca', :action => "aa" - r.connect 'cb', :controller => 'cb', :action => "ab" - r.connect 'cc', :controller => 'cc', :action => "ac" - r.connect ':controller/:action/:id' - r.connect ':controller/:action/:id.:format' + rs = ::ActionDispatch::Routing::RouteSet.new + rs.draw do + match 'ca' => 'ca#aa' + match 'cb' => 'cb#ab' + match 'cc' => 'cc#ac' + match ':controller/:action/:id' + match ':controller/:action/:id.:format' end hash = rs.recognize_path "/cc" @@ -629,22 +612,23 @@ class LegacyRouteSetTests < Test::Unit::TestCase assert_not_nil hash assert_equal %w(cc ac), [hash[:controller], hash[:action]] - rs.draw do |r| - r.connect 'cb', :controller => 'cb', :action => "ab" - r.connect 'cc', :controller => 'cc', :action => "ac" - r.connect ':controller/:action/:id' - r.connect ':controller/:action/:id.:format' + rs.draw do + match 'cb' => 'cb#ab' + match 'cc' => 'cc#ac' + match ':controller/:action/:id' + match ':controller/:action/:id.:format' end hash = rs.recognize_path "/cc" assert_not_nil hash assert_equal %w(cc ac), [hash[:controller], hash[:action]] - end end class RouteSetTest < ActiveSupport::TestCase + include RoutingTestHelpers + def set @set ||= ROUTING::RouteSet.new end @@ -656,30 +640,30 @@ class RouteSetTest < ActiveSupport::TestCase def default_route_set @default_route_set ||= begin set = ROUTING::RouteSet.new - set.draw do |map| - map.connect '/:controller/:action/:id/' + set.draw do + match '/:controller(/:action(/:id))' end set end end def test_generate_extras - set.draw { |m| m.connect ':controller/:action/:id' } + set.draw { match ':controller/(:action(/:id))' } path, extras = set.generate_extras(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world") assert_equal "/foo/bar/15", path assert_equal %w(that this), extras.map { |e| e.to_s }.sort end def test_extra_keys - set.draw { |m| m.connect ':controller/:action/:id' } + set.draw { match ':controller/:action/:id' } extras = set.extra_keys(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world") assert_equal %w(that this), extras.map { |e| e.to_s }.sort end def test_generate_extras_not_first - set.draw do |map| - map.connect ':controller/:action/:id.:format' - map.connect ':controller/:action/:id' + set.draw do + match ':controller/:action/:id.:format' + match ':controller/:action/:id' end path, extras = set.generate_extras(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world") assert_equal "/foo/bar/15", path @@ -687,17 +671,18 @@ class RouteSetTest < ActiveSupport::TestCase end def test_generate_not_first - set.draw do |map| - map.connect ':controller/:action/:id.:format' - map.connect ':controller/:action/:id' + set.draw do + match ':controller/:action/:id.:format' + match ':controller/:action/:id' end - assert_equal "/foo/bar/15?this=hello", set.generate(:controller => "foo", :action => "bar", :id => 15, :this => "hello") + assert_equal "/foo/bar/15?this=hello", + url_for(set, { :controller => "foo", :action => "bar", :id => 15, :this => "hello" }) end def test_extra_keys_not_first - set.draw do |map| - map.connect ':controller/:action/:id.:format' - map.connect ':controller/:action/:id' + set.draw do + match ':controller/:action/:id.:format' + match ':controller/:action/:id' end extras = set.extra_keys(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world") assert_equal %w(that this), extras.map { |e| e.to_s }.sort @@ -705,44 +690,44 @@ class RouteSetTest < ActiveSupport::TestCase def test_draw assert_equal 0, set.routes.size - set.draw do |map| - map.connect '/hello/world', :controller => 'a', :action => 'b' + set.draw do + match '/hello/world' => 'a#b' end assert_equal 1, set.routes.size end def test_draw_symbol_controller_name assert_equal 0, set.routes.size - set.draw do |map| - map.connect '/users/index', :controller => :users, :action => :index + set.draw do + match '/users/index' => 'users#index' end - params = set.recognize_path('/users/index', :method => :get) + set.recognize_path('/users/index', :method => :get) assert_equal 1, set.routes.size end def test_named_draw assert_equal 0, set.routes.size - set.draw do |map| - map.hello '/hello/world', :controller => 'a', :action => 'b' + set.draw do + match '/hello/world' => 'a#b', :as => 'hello' end assert_equal 1, set.routes.size assert_equal set.routes.first, set.named_routes[:hello] end def test_later_named_routes_take_precedence - set.draw do |map| - map.hello '/hello/world', :controller => 'a', :action => 'b' - map.hello '/hello', :controller => 'a', :action => 'b' + set.draw do + match '/hello/world' => 'a#b', :as => 'hello' + match '/hello' => 'a#b', :as => 'hello' end assert_equal set.routes.last, set.named_routes[:hello] end def setup_named_route_test - set.draw do |map| - map.show '/people/:id', :controller => 'people', :action => 'show' - map.index '/people', :controller => 'people', :action => 'index' - map.multi '/people/go/:foo/:bar/joe/:id', :controller => 'people', :action => 'multi' - map.users '/admin/users', :controller => 'admin/users', :action => 'index' + set.draw do + match '/people(/:id)' => 'people#show', :as => 'show' + match '/people' => 'people#index', :as => 'index' + match '/people/go/:foo/:bar/joe(/:id)' => 'people#multi', :as => 'multi' + match '/admin/users' => 'admin/users#index', :as => "users" end MockController.build(set.url_helpers).new @@ -752,15 +737,15 @@ class RouteSetTest < ActiveSupport::TestCase controller = setup_named_route_test assert_equal( - { :controller => 'people', :action => 'show', :id => 5, :use_route => :show, :only_path => false }, + { :controller => 'people', :action => 'show', :id => 5, :use_route => "show", :only_path => false }, controller.send(:hash_for_show_url, :id => 5)) assert_equal( - { :controller => 'people', :action => 'index', :use_route => :index, :only_path => false }, + { :controller => 'people', :action => 'index', :use_route => "index", :only_path => false }, controller.send(:hash_for_index_url)) assert_equal( - { :controller => 'people', :action => 'show', :id => 5, :use_route => :show, :only_path => true }, + { :controller => 'people', :action => 'show', :id => 5, :use_route => "show", :only_path => true }, controller.send(:hash_for_show_path, :id => 5) ) end @@ -776,7 +761,7 @@ class RouteSetTest < ActiveSupport::TestCase assert_equal "http://test.host/admin/users", controller.send(:users_url) assert_equal '/admin/users', controller.send(:users_path) - assert_equal '/admin/users', set.generate(controller.send(:hash_for_users_url), {:controller => 'users', :action => 'index'}) + assert_equal '/admin/users', url_for(set, controller.send(:hash_for_users_url), { :controller => 'users', :action => 'index' }) end def test_named_route_url_method_with_anchor @@ -841,30 +826,23 @@ class RouteSetTest < ActiveSupport::TestCase end def test_draw_default_route - set.draw do |map| - map.connect '/:controller/:action/:id' + set.draw do + match '/:controller/:action/:id' end assert_equal 1, set.routes.size - assert_equal '/users/show/10', set.generate(:controller => 'users', :action => 'show', :id => 10) - assert_equal '/users/index/10', set.generate(:controller => 'users', :id => 10) + assert_equal '/users/show/10', url_for(set, { :controller => 'users', :action => 'show', :id => 10 }) + assert_equal '/users/index/10', url_for(set, { :controller => 'users', :id => 10 }) assert_equal({:controller => 'users', :action => 'index', :id => '10'}, set.recognize_path('/users/index/10')) assert_equal({:controller => 'users', :action => 'index', :id => '10'}, set.recognize_path('/users/index/10/')) end - def test_draw_default_route_with_default_controller - set.draw do |map| - map.connect '/:controller/:action/:id', :controller => 'users' - end - assert_equal({:controller => 'users', :action => 'index'}, set.recognize_path('/')) - end - def test_route_with_parameter_shell - set.draw do |map| - map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+/ - map.connect '/:controller/:action/:id' + set.draw do + match 'page/:id' => 'pages#show', :id => /\d+/ + match '/:controller(/:action(/:id))' end assert_equal({:controller => 'pages', :action => 'index'}, set.recognize_path('/pages')) @@ -875,76 +853,66 @@ class RouteSetTest < ActiveSupport::TestCase assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set.recognize_path('/page/10')) end - def test_route_requirements_with_anchor_chars_are_invalid - assert_raise ArgumentError do - set.draw do |map| - map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /^\d+/ + def test_route_constraints_on_request_object_with_anchors_are_valid + assert_nothing_raised do + set.draw do + match 'page/:id' => 'pages#show', :constraints => { :host => /^foo$/ } end end + end + + def test_route_constraints_with_anchor_chars_are_invalid assert_raise ArgumentError do - set.draw do |map| - map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\A\d+/ + set.draw do + match 'page/:id' => 'pages#show', :id => /^\d+/ end end assert_raise ArgumentError do - set.draw do |map| - map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+$/ + set.draw do + match 'page/:id' => 'pages#show', :id => /\A\d+/ end end assert_raise ArgumentError do - set.draw do |map| - map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+\Z/ + set.draw do + match 'page/:id' => 'pages#show', :id => /\d+$/ end end assert_raise ArgumentError do - set.draw do |map| - map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /\d+\z/ + set.draw do + match 'page/:id' => 'pages#show', :id => /\d+\Z/ end end - end - - def test_route_requirements_with_invalid_http_method_is_invalid assert_raise ArgumentError do - set.draw do |map| - map.connect 'valid/route', :controller => 'pages', :action => 'show', :conditions => {:method => :invalid} + set.draw do + match 'page/:id' => 'pages#show', :id => /\d+\z/ end end end - def test_route_requirements_with_options_method_condition_is_valid + def test_route_constraints_with_options_method_condition_is_valid assert_nothing_raised do - set.draw do |map| - map.connect 'valid/route', :controller => 'pages', :action => 'show', :conditions => {:method => :options} - end - end - end - - def test_route_requirements_with_head_method_condition_is_invalid - assert_raise ArgumentError do - set.draw do |map| - map.connect 'valid/route', :controller => 'pages', :action => 'show', :conditions => {:method => :head} + set.draw do + match 'valid/route' => 'pages#show', :via => :options end end end def test_recognize_with_encoded_id_and_regex - set.draw do |map| - map.connect 'page/:id', :controller => 'pages', :action => 'show', :id => /[a-zA-Z0-9\+]+/ + set.draw do + match 'page/:id' => 'pages#show', :id => /[a-zA-Z0-9\+]+/ end assert_equal({:controller => 'pages', :action => 'show', :id => '10'}, set.recognize_path('/page/10')) assert_equal({:controller => 'pages', :action => 'show', :id => 'hello+world'}, set.recognize_path('/page/hello+world')) end - def test_recognize_with_conditions - set.draw do |map| - map.with_options(:controller => "people") do |people| - people.people "/people", :action => "index", :conditions => { :method => :get } - people.connect "/people", :action => "create", :conditions => { :method => :post } - people.person "/people/:id", :action => "show", :conditions => { :method => :get } - people.connect "/people/:id", :action => "update", :conditions => { :method => :put } - people.connect "/people/:id", :action => "destroy", :conditions => { :method => :delete } - end + def test_recognize_with_http_methods + set.draw do + get "/people" => "people#index", :as => "people" + post "/people" => "people#create" + get "/people/:id" => "people#show", :as => "person" + put "/people/:id" => "people#update" + delete "/people/:id" => "people#destroy" end params = set.recognize_path("/people", :method => :get) @@ -953,10 +921,10 @@ class RouteSetTest < ActiveSupport::TestCase params = set.recognize_path("/people", :method => :post) assert_equal("create", params[:action]) - params = set.recognize_path("/people", :method => :put) + params = set.recognize_path("/people/5", :method => :put) assert_equal("update", params[:action]) - assert_raise(ActionController::RoutingError) { + assert_raise(ActionController::UnknownHttpMethod) { set.recognize_path("/people", :method => :bacon) } @@ -978,10 +946,9 @@ class RouteSetTest < ActiveSupport::TestCase end def test_recognize_with_alias_in_conditions - set.draw do |map| - map.people "/people", :controller => 'people', :action => "index", - :conditions => { :method => :get } - map.root :people + set.draw do + match "/people" => 'people#index', :as => 'people', :via => :get + root :to => "people#index" end params = set.recognize_path("/people", :method => :get) @@ -994,9 +961,8 @@ class RouteSetTest < ActiveSupport::TestCase end def test_typo_recognition - set.draw do |map| - map.connect 'articles/:year/:month/:day/:title', - :controller => 'articles', :action => 'permalink', + set.draw do + match 'articles/:year/:month/:day/:title' => 'articles#permalink', :year => /\d{4}/, :day => /\d{1,2}/, :month => /\d{1,2}/ end @@ -1010,22 +976,20 @@ class RouteSetTest < ActiveSupport::TestCase def test_routing_traversal_does_not_load_extra_classes assert !Object.const_defined?("Profiler__"), "Profiler should not be loaded" - set.draw do |map| - map.connect '/profile', :controller => 'profile' + set.draw do + match '/profile' => 'profile#index' end - params = set.recognize_path("/profile") rescue nil + set.recognize_path("/profile") rescue nil assert !Object.const_defined?("Profiler__"), "Profiler should not be loaded" end def test_recognize_with_conditions_and_format - set.draw do |map| - map.with_options(:controller => "people") do |people| - people.person "/people/:id", :action => "show", :conditions => { :method => :get } - people.connect "/people/:id", :action => "update", :conditions => { :method => :put } - people.connect "/people/:id.:_format", :action => "show", :conditions => { :method => :get } - end + set.draw do + get "people/:id" => "people#show", :as => "person" + put "people/:id" => "people#update" + get "people/:id(.:format)" => "people#show" end params = set.recognize_path("/people/5", :method => :get) @@ -1038,21 +1002,21 @@ class RouteSetTest < ActiveSupport::TestCase params = set.recognize_path("/people/5.png", :method => :get) assert_equal("show", params[:action]) assert_equal("5", params[:id]) - assert_equal("png", params[:_format]) + assert_equal("png", params[:format]) end def test_generate_with_default_action - set.draw do |map| - map.connect "/people", :controller => "people" - map.connect "/people/list", :controller => "people", :action => "list" + set.draw do + match "/people", :controller => "people", :action => "index" + match "/people/list", :controller => "people", :action => "list" end - url = set.generate(:controller => "people", :action => "list") + url = url_for(set, { :controller => "people", :action => "list" }) assert_equal "/people/list", url end def test_root_map - set.draw { |map| map.root :controller => "people" } + set.draw { root :to => 'people#index' } params = set.recognize_path("", :method => :get) assert_equal("people", params[:controller]) @@ -1060,10 +1024,10 @@ class RouteSetTest < ActiveSupport::TestCase end def test_namespace - set.draw do |map| + set.draw do - map.namespace 'api' do |api| - api.route 'inventory', :controller => "products", :action => 'inventory' + namespace 'api' do + match 'inventory' => 'products#inventory' end end @@ -1074,12 +1038,10 @@ class RouteSetTest < ActiveSupport::TestCase end def test_namespaced_root_map - set.draw do |map| - - map.namespace 'api' do |api| - api.root :controller => "products" + set.draw do + namespace 'api' do + root :to => 'products#index' end - end params = set.recognize_path("/api", :method => :get) @@ -1088,9 +1050,9 @@ class RouteSetTest < ActiveSupport::TestCase end def test_namespace_with_path_prefix - set.draw do |map| - map.namespace 'api', :path_prefix => 'prefix' do |api| - api.route 'inventory', :controller => "products", :action => 'inventory' + set.draw do + scope :module => "api", :path => "prefix" do + match 'inventory' => 'products#inventory' end end @@ -1100,9 +1062,9 @@ class RouteSetTest < ActiveSupport::TestCase end def test_namespace_with_blank_path_prefix - set.draw do |map| - map.namespace 'api', :path_prefix => '' do |api| - api.route 'inventory', :controller => "products", :action => 'inventory' + set.draw do + scope :module => "api", :path => "" do + match 'inventory' => 'products#inventory' end end @@ -1112,128 +1074,129 @@ class RouteSetTest < ActiveSupport::TestCase end def test_generate_changes_controller_module - set.draw { |map| map.connect ':controller/:action/:id' } + set.draw { match ':controller/:action/:id' } current = { :controller => "bling/bloop", :action => "bap", :id => 9 } - url = set.generate({:controller => "foo/bar", :action => "baz", :id => 7}, current) - assert_equal "/foo/bar/baz/7", url - end - # def test_id_is_not_impossibly_sticky - # set.draw do |map| - # map.connect 'foo/:number', :controller => "people", :action => "index" - # map.connect ':controller/:action/:id' - # end - # - # url = set.generate({:controller => "people", :action => "index", :number => 3}, - # {:controller => "people", :action => "index", :id => "21"}) - # assert_equal "/foo/3", url - # end + assert_equal "/foo/bar/baz/7", + url_for(set, { :controller => "foo/bar", :action => "baz", :id => 7 }, current) + end def test_id_is_sticky_when_it_ought_to_be - set.draw do |map| - map.connect ':controller/:id/:action' + set.draw do + match ':controller/:id/:action' end - url = set.generate({:action => "destroy"}, {:controller => "people", :action => "show", :id => "7"}) + url = url_for(set, { :action => "destroy" }, { :controller => "people", :action => "show", :id => "7" }) assert_equal "/people/7/destroy", url end def test_use_static_path_when_possible - set.draw do |map| - map.connect 'about', :controller => "welcome", :action => "about" - map.connect ':controller/:action/:id' + set.draw do + match 'about' => "welcome#about" + match ':controller/:action/:id' end - url = set.generate({:controller => "welcome", :action => "about"}, - {:controller => "welcome", :action => "get", :id => "7"}) + url = url_for(set, { :controller => "welcome", :action => "about" }, + { :controller => "welcome", :action => "get", :id => "7" }) + assert_equal "/about", url end def test_generate - set.draw { |map| map.connect ':controller/:action/:id' } + set.draw { match ':controller/:action/:id' } args = { :controller => "foo", :action => "bar", :id => "7", :x => "y" } - assert_equal "/foo/bar/7?x=y", set.generate(args) + assert_equal "/foo/bar/7?x=y", url_for(set, args) assert_equal ["/foo/bar/7", [:x]], set.generate_extras(args) assert_equal [:x], set.extra_keys(args) end def test_generate_with_path_prefix - set.draw { |map| map.connect ':controller/:action/:id', :path_prefix => 'my' } + set.draw do + scope "my" do + match ':controller(/:action(/:id))' + end + end args = { :controller => "foo", :action => "bar", :id => "7", :x => "y" } - assert_equal "/my/foo/bar/7?x=y", set.generate(args) + assert_equal "/my/foo/bar/7?x=y", url_for(set, args) end def test_generate_with_blank_path_prefix - set.draw { |map| map.connect ':controller/:action/:id', :path_prefix => '' } + set.draw do + scope "" do + match ':controller(/:action(/:id))' + end + end args = { :controller => "foo", :action => "bar", :id => "7", :x => "y" } - assert_equal "/foo/bar/7?x=y", set.generate(args) + assert_equal "/foo/bar/7?x=y", url_for(set, args) end def test_named_routes_are_never_relative_to_modules - set.draw do |map| - map.connect "/connection/manage/:action", :controller => 'connection/manage' - map.connect "/connection/connection", :controller => "connection/connection" - map.family_connection "/connection", :controller => "connection" + set.draw do + match "/connection/manage(/:action)" => 'connection/manage#index' + match "/connection/connection" => "connection/connection#index" + match '/connection' => 'connection#index', :as => 'family_connection' end - url = set.generate({:controller => "connection"}, {:controller => 'connection/manage'}) + url = url_for(set, { :controller => "connection" }, { :controller => 'connection/manage' }) assert_equal "/connection/connection", url - url = set.generate({:use_route => :family_connection, :controller => "connection"}, {:controller => 'connection/manage'}) + url = url_for(set, { :use_route => :family_connection, :controller => "connection" }, { :controller => 'connection/manage' }) assert_equal "/connection", url end def test_action_left_off_when_id_is_recalled - set.draw do |map| - map.connect ':controller/:action/:id' + set.draw do + match ':controller(/:action(/:id))' end - assert_equal '/books', set.generate( + assert_equal '/books', url_for(set, {:controller => 'books', :action => 'index'}, {:controller => 'books', :action => 'show', :id => '10'} ) end def test_query_params_will_be_shown_when_recalled - set.draw do |map| - map.connect 'show_weblog/:parameter', :controller => 'weblog', :action => 'show' - map.connect ':controller/:action/:id' + set.draw do + match 'show_weblog/:parameter' => 'weblog#show' + match ':controller(/:action(/:id))' end - assert_equal '/weblog/edit?parameter=1', set.generate( + assert_equal '/weblog/edit?parameter=1', url_for(set, {:action => 'edit', :parameter => 1}, {:controller => 'weblog', :action => 'show', :parameter => 1} ) end def test_format_is_not_inherit - set.draw do |map| - map.connect '/posts.:format', :controller => 'posts' + set.draw do + match '/posts(.:format)' => 'posts#index' end - assert_equal '/posts', set.generate( + assert_equal '/posts', url_for(set, {:controller => 'posts'}, {:controller => 'posts', :action => 'index', :format => 'xml'} ) - assert_equal '/posts.xml', set.generate( + assert_equal '/posts.xml', url_for(set, {:controller => 'posts', :format => 'xml'}, {:controller => 'posts', :action => 'index', :format => 'xml'} ) end def test_expiry_determination_should_consider_values_with_to_param - set.draw { |map| map.connect 'projects/:project_id/:controller/:action' } - assert_equal '/projects/1/weblog/show', set.generate( - {:action => 'show', :project_id => 1}, - {:controller => 'weblog', :action => 'show', :project_id => '1'}) + set.draw { match 'projects/:project_id/:controller/:action' } + assert_equal '/projects/1/weblog/show', url_for(set, + { :action => 'show', :project_id => 1 }, + { :controller => 'weblog', :action => 'show', :project_id => '1' }) end def test_named_route_in_nested_resource - set.draw do |map| - map.resources :projects do |project| - project.milestones 'milestones', :controller => 'milestones', :action => 'index' + set.draw do + resources :projects do + member do + match 'milestones' => 'milestones#index', :as => 'milestones' + end end end @@ -1244,9 +1207,9 @@ class RouteSetTest < ActiveSupport::TestCase def test_setting_root_in_namespace_using_symbol assert_nothing_raised do - set.draw do |map| - map.namespace :admin do |admin| - admin.root :controller => 'home' + set.draw do + namespace :admin do + root :to => "home#index" end end end @@ -1254,51 +1217,47 @@ class RouteSetTest < ActiveSupport::TestCase def test_setting_root_in_namespace_using_string assert_nothing_raised do - set.draw do |map| - map.namespace 'admin' do |admin| - admin.root :controller => 'home' + set.draw do + namespace 'admin' do + root :to => "home#index" end end end end - def test_route_requirements_with_unsupported_regexp_options_must_error + def test_route_constraints_with_unsupported_regexp_options_must_error assert_raise ArgumentError do - set.draw do |map| - map.connect 'page/:name', :controller => 'pages', - :action => 'show', - :requirements => {:name => /(david|jamis)/m} + set.draw do + match 'page/:name' => 'pages#show', + :constraints => { :name => /(david|jamis)/m } end end end - def test_route_requirements_with_supported_options_must_not_error + def test_route_constraints_with_supported_options_must_not_error assert_nothing_raised do - set.draw do |map| - map.connect 'page/:name', :controller => 'pages', - :action => 'show', - :requirements => {:name => /(david|jamis)/i} + set.draw do + match 'page/:name' => 'pages#show', + :constraints => { :name => /(david|jamis)/i } end end assert_nothing_raised do - set.draw do |map| - map.connect 'page/:name', :controller => 'pages', - :action => 'show', - :requirements => {:name => / # Desperately overcommented regexp + set.draw do + match 'page/:name' => 'pages#show', + :constraints => { :name => / # Desperately overcommented regexp ( #Either david #The Creator | #Or jamis #The Deployer - )/x} + )/x } end end end def test_route_requirement_recognize_with_ignore_case - set.draw do |map| - map.connect 'page/:name', :controller => 'pages', - :action => 'show', - :requirements => {:name => /(david|jamis)/i} + set.draw do + match 'page/:name' => 'pages#show', + :constraints => {:name => /(david|jamis)/i} end assert_equal({:controller => 'pages', :action => 'show', :name => 'jamis'}, set.recognize_path('/page/jamis')) assert_raise ActionController::RoutingError do @@ -1308,26 +1267,24 @@ class RouteSetTest < ActiveSupport::TestCase end def test_route_requirement_generate_with_ignore_case - set.draw do |map| - map.connect 'page/:name', :controller => 'pages', - :action => 'show', - :requirements => {:name => /(david|jamis)/i} + set.draw do + match 'page/:name' => 'pages#show', + :constraints => {:name => /(david|jamis)/i} end - url = set.generate({:controller => 'pages', :action => 'show', :name => 'david'}) + url = url_for(set, { :controller => 'pages', :action => 'show', :name => 'david' }) assert_equal "/page/david", url assert_raise ActionController::RoutingError do - url = set.generate({:controller => 'pages', :action => 'show', :name => 'davidjamis'}) + url_for(set, { :controller => 'pages', :action => 'show', :name => 'davidjamis' }) end - url = set.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'}) + url = url_for(set, { :controller => 'pages', :action => 'show', :name => 'JAMIS' }) assert_equal "/page/JAMIS", url end def test_route_requirement_recognize_with_extended_syntax - set.draw do |map| - map.connect 'page/:name', :controller => 'pages', - :action => 'show', - :requirements => {:name => / # Desperately overcommented regexp + set.draw do + match 'page/:name' => 'pages#show', + :constraints => {:name => / # Desperately overcommented regexp ( #Either david #The Creator | #Or @@ -1344,33 +1301,10 @@ class RouteSetTest < ActiveSupport::TestCase end end - def test_route_requirement_generate_with_extended_syntax - set.draw do |map| - map.connect 'page/:name', :controller => 'pages', - :action => 'show', - :requirements => {:name => / # Desperately overcommented regexp - ( #Either - david #The Creator - | #Or - jamis #The Deployer - )/x} - end - - url = set.generate({:controller => 'pages', :action => 'show', :name => 'david'}) - assert_equal "/page/david", url - assert_raise ActionController::RoutingError do - url = set.generate({:controller => 'pages', :action => 'show', :name => 'davidjamis'}) - end - assert_raise ActionController::RoutingError do - url = set.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'}) - end - end - - def test_route_requirement_generate_with_xi_modifiers - set.draw do |map| - map.connect 'page/:name', :controller => 'pages', - :action => 'show', - :requirements => {:name => / # Desperately overcommented regexp + def test_route_requirement_with_xi_modifiers + set.draw do + match 'page/:name' => 'pages#show', + :constraints => {:name => / # Desperately overcommented regexp ( #Either david #The Creator | #Or @@ -1378,98 +1312,83 @@ class RouteSetTest < ActiveSupport::TestCase )/xi} end - url = set.generate({:controller => 'pages', :action => 'show', :name => 'JAMIS'}) - assert_equal "/page/JAMIS", url - end + assert_equal({:controller => 'pages', :action => 'show', :name => 'JAMIS'}, + set.recognize_path('/page/JAMIS')) - def test_route_requirement_recognize_with_xi_modifiers - set.draw do |map| - map.connect 'page/:name', :controller => 'pages', - :action => 'show', - :requirements => {:name => / # Desperately overcommented regexp - ( #Either - david #The Creator - | #Or - jamis #The Deployer - )/xi} - end - assert_equal({:controller => 'pages', :action => 'show', :name => 'JAMIS'}, set.recognize_path('/page/JAMIS')) + assert_equal "/page/JAMIS", + url_for(set, { :controller => 'pages', :action => 'show', :name => 'JAMIS' }) end def test_routes_with_symbols - set.draw do |map| - map.connect 'unnamed', :controller => :pages, :action => :show, :name => :as_symbol - map.named 'named', :controller => :pages, :action => :show, :name => :as_symbol + set.draw do + match 'unnamed', :controller => :pages, :action => :show, :name => :as_symbol + match 'named' , :controller => :pages, :action => :show, :name => :as_symbol, :as => :named end assert_equal({:controller => 'pages', :action => 'show', :name => :as_symbol}, set.recognize_path('/unnamed')) assert_equal({:controller => 'pages', :action => 'show', :name => :as_symbol}, set.recognize_path('/named')) end def test_regexp_chunk_should_add_question_mark_for_optionals - set.draw do |map| - map.connect '/', :controller => 'foo' - map.connect '/hello', :controller => 'bar' + set.draw do + match '/' => 'foo#index' + match '/hello' => 'bar#index' end - assert_equal '/', set.generate(:controller => 'foo') - assert_equal '/hello', set.generate(:controller => 'bar') + assert_equal '/', url_for(set, { :controller => 'foo' }) + assert_equal '/hello', url_for(set, { :controller => 'bar' }) assert_equal({:controller => "foo", :action => "index"}, set.recognize_path('/')) assert_equal({:controller => "bar", :action => "index"}, set.recognize_path('/hello')) end def test_assign_route_options_with_anchor_chars - set.draw do |map| - map.connect '/cars/:action/:person/:car/', :controller => 'cars' + set.draw do + match '/cars/:action/:person/:car/', :controller => 'cars' end - assert_equal '/cars/buy/1/2', set.generate(:controller => 'cars', :action => 'buy', :person => '1', :car => '2') + assert_equal '/cars/buy/1/2', url_for(set, { :controller => 'cars', :action => 'buy', :person => '1', :car => '2' }) assert_equal({:controller => "cars", :action => "buy", :person => "1", :car => "2"}, set.recognize_path('/cars/buy/1/2')) end def test_segmentation_of_dot_path - set.draw do |map| - map.connect '/books/:action.rss', :controller => 'books' + set.draw do + match '/books/:action.rss', :controller => 'books' end - assert_equal '/books/list.rss', set.generate(:controller => 'books', :action => 'list') + assert_equal '/books/list.rss', url_for(set, { :controller => 'books', :action => 'list' }) assert_equal({:controller => "books", :action => "list"}, set.recognize_path('/books/list.rss')) end def test_segmentation_of_dynamic_dot_path - set.draw do |map| - map.connect '/books/:action.:format', :controller => 'books' + set.draw do + match '/books(/:action(.:format))', :controller => 'books' end - assert_equal '/books/list.rss', set.generate(:controller => 'books', :action => 'list', :format => 'rss') - assert_equal '/books/list.xml', set.generate(:controller => 'books', :action => 'list', :format => 'xml') - assert_equal '/books/list', set.generate(:controller => 'books', :action => 'list') - assert_equal '/books', set.generate(:controller => 'books', :action => 'index') + assert_equal '/books/list.rss', url_for(set, { :controller => 'books', :action => 'list', :format => 'rss' }) + assert_equal '/books/list.xml', url_for(set, { :controller => 'books', :action => 'list', :format => 'xml' }) + assert_equal '/books/list', url_for(set, { :controller => 'books', :action => 'list' }) + assert_equal '/books', url_for(set, { :controller => 'books', :action => 'index' }) assert_equal({:controller => "books", :action => "list", :format => "rss"}, set.recognize_path('/books/list.rss')) assert_equal({:controller => "books", :action => "list", :format => "xml"}, set.recognize_path('/books/list.xml')) - assert_equal({:controller => "books", :action => "list"}, set.recognize_path('/books/list')) + assert_equal({:controller => "books", :action => "list"}, set.recognize_path('/books/list')) assert_equal({:controller => "books", :action => "index"}, set.recognize_path('/books')) end def test_slashes_are_implied - ['/:controller/:action/:id/', '/:controller/:action/:id', - ':controller/:action/:id', '/:controller/:action/:id/' - ].each do |path| - @set = nil - set.draw { |map| map.connect(path) } + @set = nil + set.draw { match("/:controller(/:action(/:id))") } - assert_equal '/content', set.generate(:controller => 'content', :action => 'index') - assert_equal '/content/list', set.generate(:controller => 'content', :action => 'list') - assert_equal '/content/show/1', set.generate(:controller => 'content', :action => 'show', :id => '1') + assert_equal '/content', url_for(set, { :controller => 'content', :action => 'index' }) + assert_equal '/content/list', url_for(set, { :controller => 'content', :action => 'list' }) + assert_equal '/content/show/1', url_for(set, { :controller => 'content', :action => 'show', :id => '1' }) - assert_equal({:controller => "content", :action => "index"}, set.recognize_path('/content')) - assert_equal({:controller => "content", :action => "index"}, set.recognize_path('/content/index')) - assert_equal({:controller => "content", :action => "list"}, set.recognize_path('/content/list')) - assert_equal({:controller => "content", :action => "show", :id => "1"}, set.recognize_path('/content/show/1')) - end + assert_equal({:controller => "content", :action => "index"}, set.recognize_path('/content')) + assert_equal({:controller => "content", :action => "index"}, set.recognize_path('/content/index')) + assert_equal({:controller => "content", :action => "list"}, set.recognize_path('/content/list')) + assert_equal({:controller => "content", :action => "show", :id => "1"}, set.recognize_path('/content/show/1')) end def test_default_route_recognition @@ -1493,102 +1412,102 @@ class RouteSetTest < ActiveSupport::TestCase end def test_default_route_should_omit_default_action - assert_equal '/accounts', default_route_set.generate({:controller => 'accounts', :action => 'index'}) + assert_equal '/accounts', url_for(default_route_set, { :controller => 'accounts', :action => 'index' }) end def test_default_route_should_include_default_action_when_id_present - assert_equal '/accounts/index/20', default_route_set.generate({:controller => 'accounts', :action => 'index', :id => '20'}) + assert_equal '/accounts/index/20', url_for(default_route_set, { :controller => 'accounts', :action => 'index', :id => '20' }) end def test_default_route_should_work_with_action_but_no_id - assert_equal '/accounts/list_all', default_route_set.generate({:controller => 'accounts', :action => 'list_all'}) + assert_equal '/accounts/list_all', url_for(default_route_set, { :controller => 'accounts', :action => 'list_all' }) end def test_default_route_should_uri_escape_pluses expected = { :controller => 'pages', :action => 'show', :id => 'hello world' } assert_equal expected, default_route_set.recognize_path('/pages/show/hello%20world') - assert_equal '/pages/show/hello%20world', default_route_set.generate(expected, expected) + assert_equal '/pages/show/hello%20world', url_for(default_route_set, expected) expected[:id] = 'hello+world' assert_equal expected, default_route_set.recognize_path('/pages/show/hello+world') assert_equal expected, default_route_set.recognize_path('/pages/show/hello%2Bworld') - assert_equal '/pages/show/hello+world', default_route_set.generate(expected, expected) + assert_equal '/pages/show/hello+world', url_for(default_route_set, expected) end def test_build_empty_query_string - assert_uri_equal '/foo', default_route_set.generate({:controller => 'foo'}) + assert_uri_equal '/foo', url_for(default_route_set, { :controller => 'foo' }) end def test_build_query_string_with_nil_value - assert_uri_equal '/foo', default_route_set.generate({:controller => 'foo', :x => nil}) + assert_uri_equal '/foo', url_for(default_route_set, { :controller => 'foo', :x => nil }) end def test_simple_build_query_string - assert_uri_equal '/foo?x=1&y=2', default_route_set.generate({:controller => 'foo', :x => '1', :y => '2'}) + assert_uri_equal '/foo?x=1&y=2', url_for(default_route_set, { :controller => 'foo', :x => '1', :y => '2' }) end def test_convert_ints_build_query_string - assert_uri_equal '/foo?x=1&y=2', default_route_set.generate({:controller => 'foo', :x => 1, :y => 2}) + assert_uri_equal '/foo?x=1&y=2', url_for(default_route_set, { :controller => 'foo', :x => 1, :y => 2 }) end def test_escape_spaces_build_query_string - assert_uri_equal '/foo?x=hello+world&y=goodbye+world', default_route_set.generate({:controller => 'foo', :x => 'hello world', :y => 'goodbye world'}) + assert_uri_equal '/foo?x=hello+world&y=goodbye+world', url_for(default_route_set, { :controller => 'foo', :x => 'hello world', :y => 'goodbye world' }) end def test_expand_array_build_query_string - assert_uri_equal '/foo?x[]=1&x[]=2', default_route_set.generate({:controller => 'foo', :x => [1, 2]}) + assert_uri_equal '/foo?x%5B%5D=1&x%5B%5D=2', url_for(default_route_set, { :controller => 'foo', :x => [1, 2] }) end def test_escape_spaces_build_query_string_selected_keys - assert_uri_equal '/foo?x=hello+world', default_route_set.generate({:controller => 'foo', :x => 'hello world'}) + assert_uri_equal '/foo?x=hello+world', url_for(default_route_set, { :controller => 'foo', :x => 'hello world' }) end def test_generate_with_default_params - set.draw do |map| - map.connect 'dummy/page/:page', :controller => 'dummy' - map.connect 'dummy/dots/page.:page', :controller => 'dummy', :action => 'dots' - map.connect 'ibocorp/:page', :controller => 'ibocorp', - :requirements => { :page => /\d+/ }, - :defaults => { :page => 1 } + set.draw do + match 'dummy/page/:page' => 'dummy#show' + match 'dummy/dots/page.:page' => 'dummy#dots' + match 'ibocorp(/:page)' => 'ibocorp#show', + :constraints => { :page => /\d+/ }, + :defaults => { :page => 1 } - map.connect ':controller/:action/:id' + match ':controller/:action/:id' end - assert_equal '/ibocorp', set.generate({:controller => 'ibocorp', :page => 1}) + assert_equal '/ibocorp', url_for(set, { :controller => 'ibocorp', :action => "show", :page => 1 }) end def test_generate_with_optional_params_recalls_last_request - set.draw do |map| - map.connect "blog/", :controller => "blog", :action => "index" + set.draw do + match "blog/", :controller => "blog", :action => "index" - map.connect "blog/:year/:month/:day", - :controller => "blog", - :action => "show_date", - :requirements => { :year => /(19|20)\d\d/, :month => /[01]?\d/, :day => /[0-3]?\d/ }, - :day => nil, :month => nil + match "blog(/:year(/:month(/:day)))", + :controller => "blog", + :action => "show_date", + :constraints => { :year => /(19|20)\d\d/, :month => /[01]?\d/, :day => /[0-3]?\d/ }, + :day => nil, :month => nil - map.connect "blog/show/:id", :controller => "blog", :action => "show", :id => /\d+/ - map.connect "blog/:controller/:action/:id" - map.connect "*anything", :controller => "blog", :action => "unknown_request" + match "blog/show/:id", :controller => "blog", :action => "show", :id => /\d+/ + match "blog/:controller/:action(/:id)" + match "*anything", :controller => "blog", :action => "unknown_request" end assert_equal({:controller => "blog", :action => "index"}, set.recognize_path("/blog")) assert_equal({:controller => "blog", :action => "show", :id => "123"}, set.recognize_path("/blog/show/123")) - assert_equal({:controller => "blog", :action => "show_date", :year => "2004"}, set.recognize_path("/blog/2004")) - assert_equal({:controller => "blog", :action => "show_date", :year => "2004", :month => "12"}, set.recognize_path("/blog/2004/12")) + assert_equal({:controller => "blog", :action => "show_date", :year => "2004", :day => nil, :month => nil }, set.recognize_path("/blog/2004")) + assert_equal({:controller => "blog", :action => "show_date", :year => "2004", :month => "12", :day => nil }, set.recognize_path("/blog/2004/12")) assert_equal({:controller => "blog", :action => "show_date", :year => "2004", :month => "12", :day => "25"}, set.recognize_path("/blog/2004/12/25")) assert_equal({:controller => "articles", :action => "edit", :id => "123"}, set.recognize_path("/blog/articles/edit/123")) assert_equal({:controller => "articles", :action => "show_stats"}, set.recognize_path("/blog/articles/show_stats")) - assert_equal({:controller => "blog", :action => "unknown_request", :anything => ["blog", "wibble"]}, set.recognize_path("/blog/wibble")) - assert_equal({:controller => "blog", :action => "unknown_request", :anything => ["junk"]}, set.recognize_path("/junk")) + assert_equal({:controller => "blog", :action => "unknown_request", :anything => "blog/wibble"}, set.recognize_path("/blog/wibble")) + assert_equal({:controller => "blog", :action => "unknown_request", :anything => "junk"}, set.recognize_path("/junk")) last_request = set.recognize_path("/blog/2006/07/28").freeze assert_equal({:controller => "blog", :action => "show_date", :year => "2006", :month => "07", :day => "28"}, last_request) - assert_equal("/blog/2006/07/25", set.generate({:day => 25}, last_request)) - assert_equal("/blog/2005", set.generate({:year => 2005}, last_request)) - assert_equal("/blog/show/123", set.generate({:action => "show" , :id => 123}, last_request)) - assert_equal("/blog/2006", set.generate({:year => 2006}, last_request)) - assert_equal("/blog/2006", set.generate({:year => 2006, :month => nil}, last_request)) + assert_equal("/blog/2006/07/25", url_for(set, { :day => 25 }, last_request)) + assert_equal("/blog/2005", url_for(set, { :year => 2005 }, last_request)) + assert_equal("/blog/show/123", url_for(set, { :action => "show" , :id => 123 }, last_request)) + assert_equal("/blog/2006", url_for(set, { :year => 2006 }, last_request)) + assert_equal("/blog/2006", url_for(set, { :year => 2006, :month => nil }, last_request)) end private @@ -1604,76 +1523,67 @@ class RouteSetTest < ActiveSupport::TestCase end class RackMountIntegrationTests < ActiveSupport::TestCase + include RoutingTestHelpers + Model = Struct.new(:to_param) - Mapping = lambda { |map| - map.namespace :admin do |admin| - admin.resources :users + Mapping = lambda { + namespace :admin do + resources :users, :posts end - map.namespace 'api' do |api| - api.root :controller => 'users' + namespace 'api' do + root :to => 'users#index' end - map.connect 'blog/:year/:month/:day', - :controller => 'posts', - :action => 'show_date', - :requirements => { :year => /(19|20)\d\d/, :month => /[01]?\d/, :day => /[0-3]?\d/}, - :day => nil, - :month => nil + match '/blog(/:year(/:month(/:day)))' => 'posts#show_date', + :constraints => { + :year => /(19|20)\d\d/, + :month => /[01]?\d/, + :day => /[0-3]?\d/ + }, + :day => nil, + :month => nil - map.blog('archive/:year', :controller => 'archive', :action => 'index', + match 'archive/:year', :controller => 'archive', :action => 'index', :defaults => { :year => nil }, - :requirements => { :year => /\d{4}/ } - ) + :constraints => { :year => /\d{4}/ }, + :as => "blog" - map.resources :people - map.connect 'legacy/people', :controller => 'people', :action => 'index', :legacy => 'true' + resources :people + match 'legacy/people' => "people#index", :legacy => "true" - map.connect 'symbols', :controller => :symbols, :action => :show, :name => :as_symbol - map.connect 'id_default/:id', :controller => 'foo', :action => 'id_default', :id => 1 - map.connect 'get_or_post', :controller => 'foo', :action => 'get_or_post', :conditions => { :method => [:get, :post] } - map.connect 'optional/:optional', :controller => 'posts', :action => 'index' - map.project 'projects/:project_id', :controller => 'project' - map.connect 'clients', :controller => 'projects', :action => 'index' + match 'symbols', :controller => :symbols, :action => :show, :name => :as_symbol + match 'id_default(/:id)' => "foo#id_default", :id => 1 + match 'get_or_post' => "foo#get_or_post", :via => [:get, :post] + match 'optional/:optional' => "posts#index" + match 'projects/:project_id' => "project#index", :as => "project" + match 'clients' => "projects#index" - map.connect 'ignorecase/geocode/:postalcode', :controller => 'geocode', - :action => 'show', :postalcode => /hx\d\d-\d[a-z]{2}/i - map.geocode 'extended/geocode/:postalcode', :controller => 'geocode', - :action => 'show',:requirements => { + match 'ignorecase/geocode/:postalcode' => 'geocode#show', :postalcode => /hx\d\d-\d[a-z]{2}/i + match 'extended/geocode/:postalcode' => 'geocode#show',:constraints => { :postalcode => /# Postcode format \d{5} #Prefix (-\d{4})? #Suffix /x - } + }, :as => "geocode" - map.connect '', :controller => 'news', :format => nil - map.connect 'news.:format', :controller => 'news' + match 'news(.:format)' => "news#index" - map.connect 'comment/:id/:action', :controller => 'comments', :action => 'show' - map.connect 'ws/:controller/:action/:id', :ws => true - map.connect 'account/:action', :controller => :account, :action => :subscription - map.connect 'pages/:page_id/:controller/:action/:id' - map.connect ':controller/ping', :action => 'ping' - map.connect ':controller/:action/:id' + match 'comment/:id(/:action)' => "comments#show" + match 'ws/:controller(/:action(/:id))', :ws => true + match 'account(/:action)' => "account#subscription" + match 'pages/:page_id/:controller(/:action(/:id))' + match ':controller/ping', :action => 'ping' + match ':controller(/:action(/:id))(.:format)' + root :to => "news#index" } def setup - @routes = ActionController::Routing::RouteSet.new + @routes = ActionDispatch::Routing::RouteSet.new @routes.draw(&Mapping) end - def test_add_route - @routes.clear! - - assert_raise(ActionController::RoutingError) do - @routes.draw do |map| - map.path 'file/*path', :controller => 'content', :action => 'show_file', :path => %w(fake default) - map.connect ':controller/:action/:id' - end - end - end - def test_recognize_path assert_equal({:controller => 'admin/users', :action => 'index'}, @routes.recognize_path('/admin/users', :method => :get)) assert_equal({:controller => 'admin/users', :action => 'create'}, @routes.recognize_path('/admin/users', :method => :post)) @@ -1689,8 +1599,8 @@ class RackMountIntegrationTests < ActiveSupport::TestCase assert_equal({:controller => 'api/users', :action => 'index'}, @routes.recognize_path('/api', :method => :get)) assert_equal({:controller => 'api/users', :action => 'index'}, @routes.recognize_path('/api/', :method => :get)) - assert_equal({:controller => 'posts', :action => 'show_date', :year => '2009'}, @routes.recognize_path('/blog/2009', :method => :get)) - assert_equal({:controller => 'posts', :action => 'show_date', :year => '2009', :month => '01'}, @routes.recognize_path('/blog/2009/01', :method => :get)) + assert_equal({:controller => 'posts', :action => 'show_date', :year => '2009', :month => nil, :day => nil }, @routes.recognize_path('/blog/2009', :method => :get)) + assert_equal({:controller => 'posts', :action => 'show_date', :year => '2009', :month => '01', :day => nil }, @routes.recognize_path('/blog/2009/01', :method => :get)) assert_equal({:controller => 'posts', :action => 'show_date', :year => '2009', :month => '01', :day => '01'}, @routes.recognize_path('/blog/2009/01/01', :method => :get)) assert_equal({:controller => 'archive', :action => 'index', :year => '2010'}, @routes.recognize_path('/archive/2010')) @@ -1710,7 +1620,7 @@ class RackMountIntegrationTests < ActiveSupport::TestCase assert_equal({:controller => 'symbols', :action => 'show', :name => :as_symbol}, @routes.recognize_path('/symbols')) assert_equal({:controller => 'foo', :action => 'id_default', :id => '1'}, @routes.recognize_path('/id_default/1')) assert_equal({:controller => 'foo', :action => 'id_default', :id => '2'}, @routes.recognize_path('/id_default/2')) - assert_equal({:controller => 'foo', :action => 'id_default', :id => '1'}, @routes.recognize_path('/id_default')) + assert_equal({:controller => 'foo', :action => 'id_default', :id => 1 }, @routes.recognize_path('/id_default')) assert_equal({:controller => 'foo', :action => 'get_or_post'}, @routes.recognize_path('/get_or_post', :method => :get)) assert_equal({:controller => 'foo', :action => 'get_or_post'}, @routes.recognize_path('/get_or_post', :method => :post)) assert_raise(ActionController::ActionControllerError) { @routes.recognize_path('/get_or_post', :method => :put) } @@ -1743,126 +1653,118 @@ class RackMountIntegrationTests < ActiveSupport::TestCase assert_equal({:controller => 'geocode', :action => 'show', :postalcode => '12345-1234'}, @routes.recognize_path('/extended/geocode/12345-1234')) assert_equal({:controller => 'geocode', :action => 'show', :postalcode => '12345'}, @routes.recognize_path('/extended/geocode/12345')) - assert_equal({:controller => 'news', :action => 'index', :format => nil}, @routes.recognize_path('/', :method => :get)) + assert_equal({:controller => 'news', :action => 'index' }, @routes.recognize_path('/', :method => :get)) assert_equal({:controller => 'news', :action => 'index', :format => 'rss'}, @routes.recognize_path('/news.rss', :method => :get)) assert_raise(ActionController::RoutingError) { @routes.recognize_path('/none', :method => :get) } end def test_generate - assert_equal '/admin/users', @routes.generate(:use_route => 'admin_users') - assert_equal '/admin/users', @routes.generate(:controller => 'admin/users') - assert_equal '/admin/users', @routes.generate(:controller => 'admin/users', :action => 'index') - assert_equal '/admin/users', @routes.generate({:action => 'index'}, {:controller => 'admin/users'}) - assert_equal '/admin/users', @routes.generate({:controller => 'users', :action => 'index'}, {:controller => 'admin/accounts'}) - assert_equal '/people', @routes.generate({:controller => '/people', :action => 'index'}, {:controller => 'admin/accounts'}) - - assert_equal '/admin/posts', @routes.generate({:controller => 'admin/posts'}) - assert_equal '/admin/posts/new', @routes.generate({:controller => 'admin/posts', :action => 'new'}) - - assert_equal '/blog/2009', @routes.generate(:controller => 'posts', :action => 'show_date', :year => 2009) - assert_equal '/blog/2009/1', @routes.generate(:controller => 'posts', :action => 'show_date', :year => 2009, :month => 1) - assert_equal '/blog/2009/1/1', @routes.generate(:controller => 'posts', :action => 'show_date', :year => 2009, :month => 1, :day => 1) - - assert_equal '/archive/2010', @routes.generate(:controller => 'archive', :action => 'index', :year => '2010') - assert_equal '/archive', @routes.generate(:controller => 'archive', :action => 'index') - assert_equal '/archive?year=january', @routes.generate(:controller => 'archive', :action => 'index', :year => 'january') - - assert_equal '/people', @routes.generate(:use_route => 'people') - assert_equal '/people', @routes.generate(:use_route => 'people', :controller => 'people', :action => 'index') - assert_equal '/people.xml', @routes.generate(:use_route => 'people', :controller => 'people', :action => 'index', :format => 'xml') - assert_equal '/people', @routes.generate({:use_route => 'people', :controller => 'people', :action => 'index'}, {:controller => 'people', :action => 'index'}) - assert_equal '/people', @routes.generate(:controller => 'people') - assert_equal '/people', @routes.generate(:controller => 'people', :action => 'index') - assert_equal '/people', @routes.generate({:action => 'index'}, {:controller => 'people'}) - assert_equal '/people', @routes.generate({:action => 'index'}, {:controller => 'people', :action => 'show', :id => '1'}) - assert_equal '/people', @routes.generate({:controller => 'people', :action => 'index'}, {:controller => 'people', :action => 'show', :id => '1'}) - assert_equal '/people', @routes.generate({}, {:controller => 'people', :action => 'index'}) - assert_equal '/people/1', @routes.generate({:controller => 'people', :action => 'show'}, {:controller => 'people', :action => 'show', :id => '1'}) - assert_equal '/people/new', @routes.generate(:use_route => 'new_person') - assert_equal '/people/new', @routes.generate(:controller => 'people', :action => 'new') - assert_equal '/people/1', @routes.generate(:use_route => 'person', :id => '1') - assert_equal '/people/1', @routes.generate(:controller => 'people', :action => 'show', :id => '1') - assert_equal '/people/1.xml', @routes.generate(:controller => 'people', :action => 'show', :id => '1', :format => 'xml') - assert_equal '/people/1', @routes.generate(:controller => 'people', :action => 'show', :id => 1) - assert_equal '/people/1', @routes.generate(:controller => 'people', :action => 'show', :id => Model.new('1')) - assert_equal '/people/1', @routes.generate({:action => 'show', :id => '1'}, {:controller => 'people', :action => 'index'}) - assert_equal '/people/1', @routes.generate({:action => 'show', :id => 1}, {:controller => 'people', :action => 'show', :id => '1'}) - # assert_equal '/people', @routes.generate({:controller => 'people', :action => 'index'}, {:controller => 'people', :action => 'index', :id => '1'}) - assert_equal '/people', @routes.generate({:controller => 'people', :action => 'index'}, {:controller => 'people', :action => 'show', :id => '1'}) - assert_equal '/people/1', @routes.generate({}, {:controller => 'people', :action => 'show', :id => '1'}) - assert_equal '/people/1', @routes.generate({:controller => 'people', :action => 'show'}, {:controller => 'people', :action => 'index', :id => '1'}) - assert_equal '/people/1/edit', @routes.generate(:controller => 'people', :action => 'edit', :id => '1') - assert_equal '/people/1/edit.xml', @routes.generate(:controller => 'people', :action => 'edit', :id => '1', :format => 'xml') - assert_equal '/people/1/edit', @routes.generate(:use_route => 'edit_person', :id => '1') - assert_equal '/people/1?legacy=true', @routes.generate(:controller => 'people', :action => 'show', :id => '1', :legacy => 'true') - assert_equal '/people?legacy=true', @routes.generate(:controller => 'people', :action => 'index', :legacy => 'true') - - assert_equal '/id_default/2', @routes.generate(:controller => 'foo', :action => 'id_default', :id => '2') - assert_equal '/id_default', @routes.generate(:controller => 'foo', :action => 'id_default', :id => '1') - assert_equal '/id_default', @routes.generate(:controller => 'foo', :action => 'id_default', :id => 1) - assert_equal '/id_default', @routes.generate(:controller => 'foo', :action => 'id_default') - assert_equal '/optional/bar', @routes.generate(:controller => 'posts', :action => 'index', :optional => 'bar') - assert_equal '/posts', @routes.generate(:controller => 'posts', :action => 'index') - - assert_equal '/project', @routes.generate({:controller => 'project', :action => 'index'}) - assert_equal '/projects/1', @routes.generate({:controller => 'project', :action => 'index', :project_id => '1'}) - assert_equal '/projects/1', @routes.generate({:controller => 'project', :action => 'index'}, {:project_id => '1'}) - assert_raise(ActionController::RoutingError) { @routes.generate({:use_route => 'project', :controller => 'project', :action => 'index'}) } - assert_equal '/projects/1', @routes.generate({:use_route => 'project', :controller => 'project', :action => 'index', :project_id => '1'}) - assert_equal '/projects/1', @routes.generate({:use_route => 'project', :controller => 'project', :action => 'index'}, {:project_id => '1'}) - - assert_equal '/clients', @routes.generate(:controller => 'projects', :action => 'index') - assert_equal '/clients?project_id=1', @routes.generate(:controller => 'projects', :action => 'index', :project_id => '1') - assert_equal '/clients', @routes.generate({:controller => 'projects', :action => 'index'}, {:project_id => '1'}) - assert_equal '/clients', @routes.generate({:action => 'index'}, {:controller => 'projects', :action => 'index', :project_id => '1'}) - - assert_equal '/comment/20', @routes.generate({:id => 20}, {:controller => 'comments', :action => 'show'}) - assert_equal '/comment/20', @routes.generate(:controller => 'comments', :id => 20, :action => 'show') - assert_equal '/comments/boo', @routes.generate(:controller => 'comments', :action => 'boo') - - assert_equal '/ws/posts/show/1', @routes.generate(:controller => 'posts', :action => 'show', :id => '1', :ws => true) - assert_equal '/ws/posts', @routes.generate(:controller => 'posts', :action => 'index', :ws => true) - - assert_equal '/account', @routes.generate(:controller => 'account', :action => 'subscription') - assert_equal '/account/billing', @routes.generate(:controller => 'account', :action => 'billing') - - assert_equal '/pages/1/notes/show/1', @routes.generate(:page_id => '1', :controller => 'notes', :action => 'show', :id => '1') - assert_equal '/pages/1/notes/list', @routes.generate(:page_id => '1', :controller => 'notes', :action => 'list') - assert_equal '/pages/1/notes', @routes.generate(:page_id => '1', :controller => 'notes', :action => 'index') - assert_equal '/pages/1/notes', @routes.generate(:page_id => '1', :controller => 'notes') - assert_equal '/notes', @routes.generate(:page_id => nil, :controller => 'notes') - assert_equal '/notes', @routes.generate(:controller => 'notes') - assert_equal '/notes/print', @routes.generate(:controller => 'notes', :action => 'print') - assert_equal '/notes/print', @routes.generate({}, {:controller => 'notes', :action => 'print'}) - - assert_equal '/notes/index/1', @routes.generate({:controller => 'notes'}, {:controller => 'notes', :id => '1'}) - assert_equal '/notes/index/1', @routes.generate({:controller => 'notes'}, {:controller => 'notes', :id => '1', :foo => 'bar'}) - assert_equal '/notes/index/1', @routes.generate({:controller => 'notes'}, {:controller => 'notes', :id => '1'}) - assert_equal '/notes/index/1', @routes.generate({:action => 'index'}, {:controller => 'notes', :id => '1'}) - assert_equal '/notes/index/1', @routes.generate({}, {:controller => 'notes', :id => '1'}) - assert_equal '/notes/show/1', @routes.generate({}, {:controller => 'notes', :action => 'show', :id => '1'}) - assert_equal '/notes/index/1', @routes.generate({:controller => 'notes', :id => '1'}, {:foo => 'bar'}) - assert_equal '/posts', @routes.generate({:controller => 'posts'}, {:controller => 'notes', :action => 'show', :id => '1'}) - assert_equal '/notes/list', @routes.generate({:action => 'list'}, {:controller => 'notes', :action => 'show', :id => '1'}) - - assert_equal '/posts/ping', @routes.generate(:controller => 'posts', :action => 'ping') - assert_equal '/posts/show/1', @routes.generate(:controller => 'posts', :action => 'show', :id => '1') - assert_equal '/posts', @routes.generate(:controller => 'posts') - assert_equal '/posts', @routes.generate(:controller => 'posts', :action => 'index') - assert_equal '/posts', @routes.generate({:controller => 'posts'}, {:controller => 'posts', :action => 'index'}) - assert_equal '/posts/create', @routes.generate({:action => 'create'}, {:controller => 'posts'}) - assert_equal '/posts?foo=bar', @routes.generate(:controller => 'posts', :foo => 'bar') - assert_equal '/posts?foo[]=bar&foo[]=baz', @routes.generate(:controller => 'posts', :foo => ['bar', 'baz']) - assert_equal '/posts?page=2', @routes.generate(:controller => 'posts', :page => 2) - assert_equal '/posts?q[foo][a]=b', @routes.generate(:controller => 'posts', :q => { :foo => { :a => 'b'}}) - - assert_equal '/', @routes.generate(:controller => 'news', :action => 'index') - assert_equal '/', @routes.generate(:controller => 'news', :action => 'index', :format => nil) - assert_equal '/news.rss', @routes.generate(:controller => 'news', :action => 'index', :format => 'rss') - - - assert_raise(ActionController::RoutingError) { @routes.generate({:action => 'index'}) } + assert_equal '/admin/users', url_for(@routes, { :use_route => 'admin_users' }) + assert_equal '/admin/users', url_for(@routes, { :controller => 'admin/users' }) + assert_equal '/admin/users', url_for(@routes, { :controller => 'admin/users', :action => 'index' }) + assert_equal '/admin/users', url_for(@routes, { :action => 'index' }, { :controller => 'admin/users' }) + assert_equal '/admin/users', url_for(@routes, { :controller => 'users', :action => 'index' }, { :controller => 'admin/accounts' }) + assert_equal '/people', url_for(@routes, { :controller => '/people', :action => 'index' }, { :controller => 'admin/accounts' }) + + assert_equal '/admin/posts', url_for(@routes, { :controller => 'admin/posts' }) + assert_equal '/admin/posts/new', url_for(@routes, { :controller => 'admin/posts', :action => 'new' }) + + assert_equal '/blog/2009', url_for(@routes, { :controller => 'posts', :action => 'show_date', :year => 2009 }) + assert_equal '/blog/2009/1', url_for(@routes, { :controller => 'posts', :action => 'show_date', :year => 2009, :month => 1 }) + assert_equal '/blog/2009/1/1', url_for(@routes, { :controller => 'posts', :action => 'show_date', :year => 2009, :month => 1, :day => 1 }) + + assert_equal '/archive/2010', url_for(@routes, { :controller => 'archive', :action => 'index', :year => '2010' }) + assert_equal '/archive', url_for(@routes, { :controller => 'archive', :action => 'index' }) + assert_equal '/archive?year=january', url_for(@routes, { :controller => 'archive', :action => 'index', :year => 'january' }) + + assert_equal '/people', url_for(@routes, { :controller => 'people', :action => 'index' }) + assert_equal '/people', url_for(@routes, { :action => 'index' }, { :controller => 'people' }) + assert_equal '/people', url_for(@routes, { :action => 'index' }, { :controller => 'people', :action => 'show', :id => '1' }) + assert_equal '/people', url_for(@routes, { :controller => 'people', :action => 'index' }, { :controller => 'people', :action => 'show', :id => '1' }) + assert_equal '/people', url_for(@routes, {}, { :controller => 'people', :action => 'index' }) + assert_equal '/people/1', url_for(@routes, { :controller => 'people', :action => 'show' }, { :controller => 'people', :action => 'show', :id => '1' }) + assert_equal '/people/new', url_for(@routes, { :use_route => 'new_person' }) + assert_equal '/people/new', url_for(@routes, { :controller => 'people', :action => 'new' }) + assert_equal '/people/1', url_for(@routes, { :use_route => 'person', :id => '1' }) + assert_equal '/people/1', url_for(@routes, { :controller => 'people', :action => 'show', :id => '1' }) + assert_equal '/people/1.xml', url_for(@routes, { :controller => 'people', :action => 'show', :id => '1', :format => 'xml' }) + assert_equal '/people/1', url_for(@routes, { :controller => 'people', :action => 'show', :id => 1 }) + assert_equal '/people/1', url_for(@routes, { :controller => 'people', :action => 'show', :id => Model.new('1') }) + assert_equal '/people/1', url_for(@routes, { :action => 'show', :id => '1' }, { :controller => 'people', :action => 'index' }) + assert_equal '/people/1', url_for(@routes, { :action => 'show', :id => 1 }, { :controller => 'people', :action => 'show', :id => '1' }) + assert_equal '/people', url_for(@routes, { :controller => 'people', :action => 'index' }, { :controller => 'people', :action => 'show', :id => '1' }) + assert_equal '/people/1', url_for(@routes, {}, { :controller => 'people', :action => 'show', :id => '1' }) + assert_equal '/people/1', url_for(@routes, { :controller => 'people', :action => 'show' }, { :controller => 'people', :action => 'index', :id => '1' }) + assert_equal '/people/1/edit', url_for(@routes, { :controller => 'people', :action => 'edit', :id => '1' }) + assert_equal '/people/1/edit.xml', url_for(@routes, { :controller => 'people', :action => 'edit', :id => '1', :format => 'xml' }) + assert_equal '/people/1/edit', url_for(@routes, { :use_route => 'edit_person', :id => '1' }) + assert_equal '/people/1?legacy=true', url_for(@routes, { :controller => 'people', :action => 'show', :id => '1', :legacy => 'true' }) + assert_equal '/people?legacy=true', url_for(@routes, { :controller => 'people', :action => 'index', :legacy => 'true' }) + + assert_equal '/id_default/2', url_for(@routes, { :controller => 'foo', :action => 'id_default', :id => '2' }) + assert_equal '/id_default', url_for(@routes, { :controller => 'foo', :action => 'id_default', :id => '1' }) + assert_equal '/id_default', url_for(@routes, { :controller => 'foo', :action => 'id_default', :id => 1 }) + assert_equal '/id_default', url_for(@routes, { :controller => 'foo', :action => 'id_default' }) + assert_equal '/optional/bar', url_for(@routes, { :controller => 'posts', :action => 'index', :optional => 'bar' }) + assert_equal '/posts', url_for(@routes, { :controller => 'posts', :action => 'index' }) + + assert_equal '/project', url_for(@routes, { :controller => 'project', :action => 'index' }) + assert_equal '/projects/1', url_for(@routes, { :controller => 'project', :action => 'index', :project_id => '1' }) + assert_equal '/projects/1', url_for(@routes, { :controller => 'project', :action => 'index'}, {:project_id => '1' }) + assert_raise(ActionController::RoutingError) { url_for(@routes, { :use_route => 'project', :controller => 'project', :action => 'index' }) } + assert_equal '/projects/1', url_for(@routes, { :use_route => 'project', :controller => 'project', :action => 'index', :project_id => '1' }) + assert_equal '/projects/1', url_for(@routes, { :use_route => 'project', :controller => 'project', :action => 'index' }, { :project_id => '1' }) + + assert_equal '/clients', url_for(@routes, { :controller => 'projects', :action => 'index' }) + assert_equal '/clients?project_id=1', url_for(@routes, { :controller => 'projects', :action => 'index', :project_id => '1' }) + assert_equal '/clients', url_for(@routes, { :controller => 'projects', :action => 'index' }, { :project_id => '1' }) + assert_equal '/clients', url_for(@routes, { :action => 'index' }, { :controller => 'projects', :action => 'index', :project_id => '1' }) + + assert_equal '/comment/20', url_for(@routes, { :id => 20 }, { :controller => 'comments', :action => 'show' }) + assert_equal '/comment/20', url_for(@routes, { :controller => 'comments', :id => 20, :action => 'show' }) + assert_equal '/comments/boo', url_for(@routes, { :controller => 'comments', :action => 'boo' }) + + assert_equal '/ws/posts/show/1', url_for(@routes, { :controller => 'posts', :action => 'show', :id => '1', :ws => true }) + assert_equal '/ws/posts', url_for(@routes, { :controller => 'posts', :action => 'index', :ws => true }) + + assert_equal '/account', url_for(@routes, { :controller => 'account', :action => 'subscription' }) + assert_equal '/account/billing', url_for(@routes, { :controller => 'account', :action => 'billing' }) + + assert_equal '/pages/1/notes/show/1', url_for(@routes, { :page_id => '1', :controller => 'notes', :action => 'show', :id => '1' }) + assert_equal '/pages/1/notes/list', url_for(@routes, { :page_id => '1', :controller => 'notes', :action => 'list' }) + assert_equal '/pages/1/notes', url_for(@routes, { :page_id => '1', :controller => 'notes', :action => 'index' }) + assert_equal '/pages/1/notes', url_for(@routes, { :page_id => '1', :controller => 'notes' }) + assert_equal '/notes', url_for(@routes, { :page_id => nil, :controller => 'notes' }) + assert_equal '/notes', url_for(@routes, { :controller => 'notes' }) + assert_equal '/notes/print', url_for(@routes, { :controller => 'notes', :action => 'print' }) + assert_equal '/notes/print', url_for(@routes, {}, { :controller => 'notes', :action => 'print' }) + + assert_equal '/notes/index/1', url_for(@routes, { :controller => 'notes' }, { :controller => 'notes', :id => '1' }) + assert_equal '/notes/index/1', url_for(@routes, { :controller => 'notes' }, { :controller => 'notes', :id => '1', :foo => 'bar' }) + assert_equal '/notes/index/1', url_for(@routes, { :controller => 'notes' }, { :controller => 'notes', :id => '1' }) + assert_equal '/notes/index/1', url_for(@routes, { :action => 'index' }, { :controller => 'notes', :id => '1' }) + assert_equal '/notes/index/1', url_for(@routes, {}, { :controller => 'notes', :id => '1' }) + assert_equal '/notes/show/1', url_for(@routes, {}, { :controller => 'notes', :action => 'show', :id => '1' }) + assert_equal '/notes/index/1', url_for(@routes, { :controller => 'notes', :id => '1' }, { :foo => 'bar' }) + assert_equal '/posts', url_for(@routes, { :controller => 'posts' }, { :controller => 'notes', :action => 'show', :id => '1' }) + assert_equal '/notes/list', url_for(@routes, { :action => 'list' }, { :controller => 'notes', :action => 'show', :id => '1' }) + + assert_equal '/posts/ping', url_for(@routes, { :controller => 'posts', :action => 'ping' }) + assert_equal '/posts/show/1', url_for(@routes, { :controller => 'posts', :action => 'show', :id => '1' }) + assert_equal '/posts', url_for(@routes, { :controller => 'posts' }) + assert_equal '/posts', url_for(@routes, { :controller => 'posts', :action => 'index' }) + assert_equal '/posts', url_for(@routes, { :controller => 'posts' }, { :controller => 'posts', :action => 'index' }) + assert_equal '/posts/create', url_for(@routes, { :action => 'create' }, { :controller => 'posts' }) + assert_equal '/posts?foo=bar', url_for(@routes, { :controller => 'posts', :foo => 'bar' }) + assert_equal '/posts?foo%5B%5D=bar&foo%5B%5D=baz', url_for(@routes, { :controller => 'posts', :foo => ['bar', 'baz'] }) + assert_equal '/posts?page=2', url_for(@routes, { :controller => 'posts', :page => 2 }) + assert_equal '/posts?q%5Bfoo%5D%5Ba%5D=b', url_for(@routes, { :controller => 'posts', :q => { :foo => { :a => 'b'}} }) + + assert_equal '/news.rss', url_for(@routes, { :controller => 'news', :action => 'index', :format => 'rss' }) + + + assert_raise(ActionController::RoutingError) { url_for(@routes, { :action => 'index' }) } end def test_generate_extras diff --git a/actionpack/test/controller/runner_test.rb b/actionpack/test/controller/runner_test.rb new file mode 100644 index 0000000000..24c220dcd5 --- /dev/null +++ b/actionpack/test/controller/runner_test.rb @@ -0,0 +1,22 @@ +require 'abstract_unit' +require 'action_dispatch/testing/integration' + +module ActionDispatch + class RunnerTest < Test::Unit::TestCase + class MyRunner + include Integration::Runner + + def initialize(session) + @integration_session = session + end + + def hi; end + end + + def test_respond_to? + runner = MyRunner.new(Class.new { def x; end }.new) + assert runner.respond_to?(:hi) + assert runner.respond_to?(:x) + end + end +end diff --git a/actionpack/test/controller/selector_test.rb b/actionpack/test/controller/selector_test.rb index 5a5dc840b5..8ce9e43402 100644 --- a/actionpack/test/controller/selector_test.rb +++ b/actionpack/test/controller/selector_test.rb @@ -437,7 +437,7 @@ class SelectorTest < Test::Unit::TestCase assert_equal "4", @matches[1].attributes["id"] end - + def test_first_and_last parse(%Q{<table><thead></thead><tr id="1"></tr><tr id="2"></tr><tr id="3"></tr><tr id="4"></tr></table>}) # First child. @@ -471,7 +471,7 @@ class SelectorTest < Test::Unit::TestCase end - def test_first_and_last + def test_only_child_and_only_type_first_and_last # Only child. parse(%Q{<table><tr></tr></table>}) select("table:only-child") @@ -503,7 +503,7 @@ class SelectorTest < Test::Unit::TestCase assert_equal 1, @matches.size end - + def test_content parse(%Q{<div> </div>}) select("div:content()") @@ -582,7 +582,7 @@ class SelectorTest < Test::Unit::TestCase assert_equal "foo", @matches[0].attributes["title"] end - + def test_pseudo_class_negation parse(%Q{<div><p id="1"></p><p id="2"></p></div>}) select("p") @@ -594,7 +594,7 @@ class SelectorTest < Test::Unit::TestCase assert_equal 1, @matches.size assert_equal "1", @matches[0].attributes["id"] end - + def test_negation_details parse(%Q{<p id="1"></p><p id="2"></p><p id="3"></p>}) diff --git a/actionpack/test/controller/test_test.rb b/actionpack/test/controller/test_test.rb index 13c9d9ee38..edda0d0a30 100644 --- a/actionpack/test/controller/test_test.rb +++ b/actionpack/test/controller/test_test.rb @@ -135,6 +135,11 @@ XML @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new @request.env['PATH_INFO'] = nil + @routes = ActionDispatch::Routing::RouteSet.new.tap do |r| + r.draw do + match ':controller(/:action(/:id))' + end + end end def test_raw_post_handling @@ -454,18 +459,26 @@ XML def test_assert_routing_with_method with_routing do |set| - set.draw { |map| map.resources(:content) } + set.draw { resources(:content) } assert_routing({ :method => 'post', :path => 'content' }, { :controller => 'content', :action => 'create' }) end end def test_assert_routing_in_module - assert_routing 'admin/user', :controller => 'admin/user', :action => 'index' + with_routing do |set| + set.draw do + namespace :admin do + match 'user' => 'user#index' + end + end + + assert_routing 'admin/user', :controller => 'admin/user', :action => 'index' + end end - + def test_assert_routing_with_glob with_routing do |set| - set.draw { |map| match('*path' => "pages#show") } + set.draw { match('*path' => "pages#show") } assert_routing('/company/about', { :controller => 'pages', :action => 'show', :path => 'company/about' }) end end @@ -487,7 +500,7 @@ XML def test_array_path_parameter_handled_properly with_routing do |set| - set.draw do |map| + set.draw do match 'file/*path', :to => 'test_test/test#test_params' match ':controller/:action' end @@ -546,7 +559,15 @@ XML assert_equal "bar", @request.params[:foo] @request.recycle! post :no_op - assert @request.params[:foo].blank? + assert_blank @request.params[:foo] + end + + def test_symbolized_path_params_reset_after_request + get :test_params, :id => "foo" + assert_equal "foo", @request.symbolized_path_parameters[:id] + @request.recycle! + get :test_params + assert_nil @request.symbolized_path_parameters[:id] end def test_should_have_knowledge_of_client_side_cookie_state_even_if_they_are_not_set @@ -570,7 +591,7 @@ XML assert false, "expected RuntimeError, got nothing" rescue RuntimeError => error assert true - assert_match %r{@#{variable} is nil}, error.message + assert_match(%r{@#{variable} is nil}, error.message) rescue => error assert false, "expected RuntimeError, got #{error.class}" end @@ -653,13 +674,6 @@ XML assert_redirected_to 'created resource' end end - - def test_binary_content_works_with_send_file - get :test_send_file - assert_deprecated do - assert_nothing_raised(NoMethodError) { @response.binary_content } - end - end end class InferringClassNameTest < ActionController::TestCase @@ -694,7 +708,7 @@ class NamedRoutesControllerTest < ActionController::TestCase def test_should_be_able_to_use_named_routes_before_a_request_is_done with_routing do |set| - set.draw { |map| resources :contents } + set.draw { resources :contents } assert_equal 'http://test.host/contents/new', new_content_url assert_equal 'http://test.host/contents/1', content_url(:id => 1) end diff --git a/actionpack/test/controller/url_for_test.rb b/actionpack/test/controller/url_for_test.rb index 71a4a43477..3f3d6dcc2f 100644 --- a/actionpack/test/controller/url_for_test.rb +++ b/actionpack/test/controller/url_for_test.rb @@ -5,7 +5,7 @@ module AbstractController class UrlForTests < ActionController::TestCase class W - include SharedTestRoutes.url_helpers + include ActionDispatch::Routing::RouteSet.new.tap { |r| r.draw { match ':controller(/:action(/:id(.:format)))' } }.url_helpers end def teardown @@ -17,7 +17,7 @@ module AbstractController end def test_exception_is_thrown_without_host - assert_raise RuntimeError do + assert_raise ArgumentError do W.new.url_for :controller => 'c', :action => 'a', :id => 'i' end end @@ -60,6 +60,27 @@ module AbstractController ) end + def test_subdomain_may_be_changed + add_host! + assert_equal('http://api.basecamphq.com/c/a/i', + W.new.url_for(:subdomain => 'api', :controller => 'c', :action => 'a', :id => 'i') + ) + end + + def test_domain_may_be_changed + add_host! + assert_equal('http://www.37signals.com/c/a/i', + W.new.url_for(:domain => '37signals.com', :controller => 'c', :action => 'a', :id => 'i') + ) + end + + def test_tld_length_may_be_changed + add_host! + assert_equal('http://mobile.www.basecamphq.com/c/a/i', + W.new.url_for(:subdomain => 'mobile', :tld_length => 2, :controller => 'c', :action => 'a', :id => 'i') + ) + end + def test_port add_host! assert_equal('http://www.basecamphq.com:3000/c/a/i', @@ -74,16 +95,29 @@ module AbstractController ) end - def test_protocol_with_and_without_separator + def test_protocol_with_and_without_separators add_host! assert_equal('https://www.basecamphq.com/c/a/i', W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https') ) assert_equal('https://www.basecamphq.com/c/a/i', + W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https:') + ) + assert_equal('https://www.basecamphq.com/c/a/i', W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https://') ) end + def test_without_protocol + add_host! + assert_equal('//www.basecamphq.com/c/a/i', + W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => '//') + ) + assert_equal('//www.basecamphq.com/c/a/i', + W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => false) + ) + end + def test_trailing_slash add_host! options = {:controller => 'foo', :trailing_slash => true, :action => 'bar', :id => '33'} @@ -130,7 +164,7 @@ module AbstractController def test_named_routes with_routing do |set| - set.draw do |map| + set.draw do match 'this/is/verbose', :to => 'home#index', :as => :no_args match 'home/sweet/home/:user', :to => 'home#index', :as => :home end @@ -151,7 +185,7 @@ module AbstractController def test_relative_url_root_is_respected_for_named_routes with_routing do |set| - set.draw do |map| + set.draw do match '/home/sweet/home/:user', :to => 'home#index', :as => :home end @@ -165,7 +199,7 @@ module AbstractController def test_only_path with_routing do |set| - set.draw do |map| + set.draw do match 'home/sweet/home/:user', :to => 'home#index', :as => :home match ':controller/:action/:id' end @@ -219,7 +253,7 @@ module AbstractController def test_hash_recursive_and_array_parameters url = W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :id => 101, :query => {:person => {:name => 'Bob', :position => ['prof', 'art director']}, :hobby => 'piercing'}) - assert_match %r(^/c/a/101), url + assert_match(%r(^/c/a/101), url) params = extract_params(url) assert_equal params[0], { 'query[hobby]' => 'piercing' }.to_query assert_equal params[1], { 'query[person][name]' => 'Bob' }.to_query @@ -233,7 +267,7 @@ module AbstractController def test_named_routes_with_nil_keys with_routing do |set| - set.draw do |map| + set.draw do match 'posts.:format', :to => 'posts#index', :as => :posts match '/', :to => 'posts#index', :as => :main end @@ -277,6 +311,14 @@ module AbstractController assert_equal("/c/a", W.new.url_for(HashWithIndifferentAccess.new('controller' => 'c', 'action' => 'a', 'only_path' => true))) end + def test_url_params_with_nil_to_param_are_not_in_url + assert_equal("/c/a", W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :id => Struct.new(:to_param).new(nil))) + end + + def test_false_url_params_are_included_in_query + assert_equal("/c/a?show=false", W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :show => false)) + end + private def extract_params(url) url.split('?', 2).last.split('&').sort diff --git a/actionpack/test/controller/url_rewriter_test.rb b/actionpack/test/controller/url_rewriter_test.rb index a8d7b75372..89de4c1da4 100644 --- a/actionpack/test/controller/url_rewriter_test.rb +++ b/actionpack/test/controller/url_rewriter_test.rb @@ -19,6 +19,11 @@ class UrlRewriterTests < ActionController::TestCase @request = ActionController::TestRequest.new @params = {} @rewriter = Rewriter.new(@request) #.new(@request, @params) + @routes = ActionDispatch::Routing::RouteSet.new.tap do |r| + r.draw do + match ':controller(/:action(/:id))' + end + end end def test_port diff --git a/actionpack/test/controller/view_paths_test.rb b/actionpack/test/controller/view_paths_test.rb index b8972b04b6..edfcb5cc4d 100644 --- a/actionpack/test/controller/view_paths_test.rb +++ b/actionpack/test/controller/view_paths_test.rb @@ -20,7 +20,7 @@ class ViewLoadPathsTest < ActionController::TestCase layout 'test/sub' def hello_world; render(:template => 'test/hello_world'); end end - + def setup # TestController.view_paths = nil @@ -64,7 +64,7 @@ class ViewLoadPathsTest < ActionController::TestCase @controller.append_view_path(%w(bar baz)) assert_paths(FIXTURE_LOAD_PATH, "foo", "bar", "baz") - + @controller.append_view_path(FIXTURE_LOAD_PATH) assert_paths(FIXTURE_LOAD_PATH, "foo", "bar", "baz", FIXTURE_LOAD_PATH) end diff --git a/actionpack/test/controller/webservice_test.rb b/actionpack/test/controller/webservice_test.rb index 5942950b15..621fb79915 100644 --- a/actionpack/test/controller/webservice_test.rb +++ b/actionpack/test/controller/webservice_test.rb @@ -1,6 +1,6 @@ require 'abstract_unit' -class WebServiceTest < ActionController::IntegrationTest +class WebServiceTest < ActionDispatch::IntegrationTest class TestController < ActionController::Base def assign_parameters if params[:full] @@ -24,12 +24,13 @@ class WebServiceTest < ActionController::IntegrationTest def setup @controller = TestController.new + @integration_session = nil end def test_check_parameters with_test_route_set do get "/" - assert @controller.response.body.blank? + assert_blank @controller.response.body end end @@ -161,7 +162,7 @@ class WebServiceTest < ActionController::IntegrationTest def test_use_xml_ximple_with_empty_request with_test_route_set do assert_nothing_raised { post "/", "", {'CONTENT_TYPE' => 'application/xml'} } - assert @controller.response.body.blank? + assert_blank @controller.response.body end end @@ -215,7 +216,7 @@ class WebServiceTest < ActionController::IntegrationTest def test_typecast_as_yaml with_test_route_set do with_params_parsers Mime::YAML => :yaml do - yaml = <<-YAML + yaml = (<<-YAML).strip --- data: a: 15 @@ -254,7 +255,7 @@ class WebServiceTest < ActionController::IntegrationTest def with_test_route_set with_routing do |set| - set.draw do |map| + set.draw do match '/', :to => 'web_service_test/test#assign_parameters' end yield |