diff options
Diffstat (limited to 'actionpack/test')
53 files changed, 1019 insertions, 1324 deletions
diff --git a/actionpack/test/abstract_controller/abstract_controller_test.rb b/actionpack/test/abstract_controller/abstract_controller_test.rb index 9438a4dfc9..7991436703 100644 --- a/actionpack/test/abstract_controller/abstract_controller_test.rb +++ b/actionpack/test/abstract_controller/abstract_controller_test.rb @@ -19,8 +19,9 @@ module AbstractController class TestBasic < ActiveSupport::TestCase test "dispatching works" do - result = Me.new.process(:index) - assert_equal "Hello world", result.response_body + controller = Me.new + controller.process(:index) + assert_equal "Hello world", controller.response_body end end @@ -67,29 +68,33 @@ module AbstractController end class TestRenderingController < ActiveSupport::TestCase + def setup + @controller = Me2.new + end + test "rendering templates works" do - result = Me2.new.process(:index) - assert_equal "Hello from index.erb", result.response_body + @controller.process(:index) + assert_equal "Hello from index.erb", @controller.response_body end test "rendering passes ivars to the view" do - result = Me2.new.process(:action_with_ivars) - assert_equal "Hello from index_with_ivars.erb", result.response_body + @controller.process(:action_with_ivars) + assert_equal "Hello from index_with_ivars.erb", @controller.response_body end test "rendering with no template name" do - result = Me2.new.process(:naked_render) - assert_equal "Hello from naked_render.erb", result.response_body + @controller.process(:naked_render) + assert_equal "Hello from naked_render.erb", @controller.response_body end test "rendering to a rack body" do - result = Me2.new.process(:rendering_to_body) - assert_equal "Hello from naked_render.erb", result.response_body + @controller.process(:rendering_to_body) + assert_equal "Hello from naked_render.erb", @controller.response_body end test "rendering to a string" do - result = Me2.new.process(:rendering_to_string) - assert_equal "Hello from naked_render.erb", result.response_body + @controller.process(:rendering_to_string) + assert_equal "Hello from naked_render.erb", @controller.response_body end end @@ -119,14 +124,18 @@ module AbstractController end class TestPrefixedViews < ActiveSupport::TestCase + def setup + @controller = Me3.new + end + test "templates are located inside their 'prefix' folder" do - result = Me3.new.process(:index) - assert_equal "Hello from me3/index.erb", result.response_body + @controller.process(:index) + assert_equal "Hello from me3/index.erb", @controller.response_body end test "templates included their format" do - result = Me3.new.process(:formatted) - assert_equal "Hello from me3/formatted.html.erb", result.response_body + @controller.process(:formatted) + assert_equal "Hello from me3/formatted.html.erb", @controller.response_body end end @@ -168,8 +177,9 @@ module AbstractController class TestLayouts < ActiveSupport::TestCase test "layouts are included" do - result = Me4.new.process(:index) - assert_equal "Me4 Enter : Hello from me4/index.erb : Exit", result.response_body + controller = Me4.new + result = controller.process(:index) + assert_equal "Me4 Enter : Hello from me4/index.erb : Exit", controller.response_body end end @@ -203,10 +213,11 @@ module AbstractController end class TestRespondToAction < ActiveSupport::TestCase - + def assert_dispatch(klass, body = "success", action = :index) - response = klass.new.process(action).response_body - assert_equal body, response + controller = klass.new + controller.process(action) + assert_equal body, controller.response_body end test "an arbitrary method is available as an action by default" do diff --git a/actionpack/test/abstract_controller/callbacks_test.rb b/actionpack/test/abstract_controller/callbacks_test.rb index 817f60f7d1..8f62adce8c 100644 --- a/actionpack/test/abstract_controller/callbacks_test.rb +++ b/actionpack/test/abstract_controller/callbacks_test.rb @@ -19,10 +19,11 @@ module AbstractController end end - class TestCallbacks < ActiveSupport::TestCase + class TestCallbacks1 < ActiveSupport::TestCase test "basic callbacks work" do - result = Callback1.new.process(:index) - assert_equal "Hello world", result.response_body + controller = Callback1.new + result = controller.process(:index) + assert_equal "Hello world", controller.response_body end end @@ -50,20 +51,24 @@ module AbstractController end end - class TestCallbacks < ActiveSupport::TestCase + class TestCallbacks2 < ActiveSupport::TestCase + def setup + @controller = Callback2.new + end + test "before_filter works" do - result = Callback2.new.process(:index) - assert_equal "Hello world", result.response_body + result = @controller.process(:index) + assert_equal "Hello world", @controller.response_body end test "after_filter works" do - result = Callback2.new.process(:index) - assert_equal "Goodbye", result.instance_variable_get("@second") + @controller.process(:index) + assert_equal "Goodbye", @controller.instance_variable_get("@second") end test "around_filter works" do - result = Callback2.new.process(:index) - assert_equal "FIRSTSECOND", result.instance_variable_get("@aroundz") + @controller.process(:index) + assert_equal "FIRSTSECOND", @controller.instance_variable_get("@aroundz") end end @@ -81,15 +86,19 @@ module AbstractController end end - class TestCallbacks < ActiveSupport::TestCase + class TestCallbacks3 < ActiveSupport::TestCase + def setup + @controller = Callback3.new + end + test "before_filter works with procs" do - result = Callback3.new.process(:index) - assert_equal "Hello world", result.response_body + result = @controller.process(:index) + assert_equal "Hello world", @controller.response_body end test "after_filter works with procs" do - result = Callback3.new.process(:index) - assert_equal "Goodbye", result.instance_variable_get("@second") + result = @controller.process(:index) + assert_equal "Goodbye", @controller.instance_variable_get("@second") end end @@ -116,20 +125,24 @@ module AbstractController end end - class TestCallbacks < ActiveSupport::TestCase + class TestCallbacksWithConditions < ActiveSupport::TestCase + def setup + @controller = CallbacksWithConditions.new + end + test "when :only is specified, a before filter is triggered on that action" do - result = CallbacksWithConditions.new.process(:index) - assert_equal "Hello, World", result.response_body + @controller.process(:index) + assert_equal "Hello, World", @controller.response_body end test "when :only is specified, a before filter is not triggered on other actions" do - result = CallbacksWithConditions.new.process(:sekrit_data) - assert_equal "true", result.response_body + @controller.process(:sekrit_data) + assert_equal "true", @controller.response_body end test "when :except is specified, an after filter is not triggered on that action" do - result = CallbacksWithConditions.new.process(:index) - assert_nil result.instance_variable_get("@authenticated") + result = @controller.process(:index) + assert_nil @controller.instance_variable_get("@authenticated") end end @@ -156,20 +169,24 @@ module AbstractController end end - class TestCallbacks < ActiveSupport::TestCase + class TestCallbacksWithArrayConditions < ActiveSupport::TestCase + def setup + @controller = CallbacksWithArrayConditions.new + end + test "when :only is specified with an array, a before filter is triggered on that action" do - result = CallbacksWithArrayConditions.new.process(:index) - assert_equal "Hello, World", result.response_body + result = @controller.process(:index) + assert_equal "Hello, World", @controller.response_body end test "when :only is specified with an array, a before filter is not triggered on other actions" do - result = CallbacksWithArrayConditions.new.process(:sekrit_data) - assert_equal "true", result.response_body + result = @controller.process(:sekrit_data) + assert_equal "true", @controller.response_body end test "when :except is specified with an array, an after filter is not triggered on that action" do - result = CallbacksWithArrayConditions.new.process(:index) - assert_nil result.instance_variable_get("@authenticated") + result = @controller.process(:index) + assert_nil @controller.instance_variable_get("@authenticated") end end @@ -181,15 +198,19 @@ module AbstractController end end - class TestCallbacks < ActiveSupport::TestCase + class TestCallbacksWithChangedConditions < ActiveSupport::TestCase + def setup + @controller = ChangedConditions.new + end + test "when a callback is modified in a child with :only, it works for the :only action" do - result = ChangedConditions.new.process(:index) - assert_equal "Hello world", result.response_body + result = @controller.process(:index) + assert_equal "Hello world", @controller.response_body end test "when a callback is modified in a child with :only, it does not work for other actions" do - result = ChangedConditions.new.process(:not_index) - assert_equal "", result.response_body + result = @controller.process(:not_index) + assert_equal "", @controller.response_body end end @@ -207,8 +228,9 @@ module AbstractController class TestHalting < ActiveSupport::TestCase test "when a callback sets the response body, the action should not be invoked" do - result = SetsResponseBody.new.process(:index) - assert_equal "Success", result.response_body + controller = SetsResponseBody.new + controller.process(:index) + assert_equal "Success", controller.response_body end end diff --git a/actionpack/test/abstract_controller/helper_test.rb b/actionpack/test/abstract_controller/helper_test.rb index e9a60c0307..34a10cecc9 100644 --- a/actionpack/test/abstract_controller/helper_test.rb +++ b/actionpack/test/abstract_controller/helper_test.rb @@ -34,8 +34,9 @@ module AbstractController class TestHelpers < ActiveSupport::TestCase def test_helpers - result = MyHelpers1.new.process(:index) - assert_equal "Hello World : Included", result.response_body + controller = MyHelpers1.new + controller.process(:index) + assert_equal "Hello World : Included", controller.response_body end end diff --git a/actionpack/test/abstract_controller/layouts_test.rb b/actionpack/test/abstract_controller/layouts_test.rb index 42f73faa61..995aac7fad 100644 --- a/actionpack/test/abstract_controller/layouts_test.rb +++ b/actionpack/test/abstract_controller/layouts_test.rb @@ -143,13 +143,15 @@ module AbstractControllerTests class TestBase < ActiveSupport::TestCase test "when no layout is specified, and no default is available, render without a layout" do - result = Blank.new.process(:index) - assert_equal "Hello blank!", result.response_body + controller = Blank.new + controller.process(:index) + assert_equal "Hello blank!", controller.response_body end test "when layout is specified as a string, render with that layout" do - result = WithString.new.process(:index) - assert_equal "With String Hello string!", result.response_body + controller = WithString.new + controller.process(:index) + assert_equal "With String Hello string!", controller.response_body end test "when layout is specified as a string, but the layout is missing, raise an exception" do @@ -157,23 +159,27 @@ module AbstractControllerTests end test "when layout is specified as false, do not use a layout" do - result = WithFalseLayout.new.process(:index) - assert_equal "Hello false!", result.response_body + controller = WithFalseLayout.new + controller.process(:index) + assert_equal "Hello false!", controller.response_body end test "when layout is specified as nil, do not use a layout" do - result = WithNilLayout.new.process(:index) - assert_equal "Hello nil!", result.response_body + controller = WithNilLayout.new + controller.process(:index) + assert_equal "Hello nil!", controller.response_body end test "when layout is specified as a symbol, call the requested method and use the layout returned" do - result = WithSymbol.new.process(:index) - assert_equal "OMGHI2U Hello symbol!", result.response_body + controller = WithSymbol.new + controller.process(:index) + assert_equal "OMGHI2U Hello symbol!", controller.response_body end test "when layout is specified as a symbol and the method returns nil, don't use a layout" do - result = WithSymbolReturningNil.new.process(:index) - assert_equal "Hello nilz!", result.response_body + controller = WithSymbolReturningNil.new + controller.process(:index) + assert_equal "Hello nilz!", controller.response_body end test "when the layout is specified as a symbol and the method doesn't exist, raise an exception" do @@ -185,29 +191,34 @@ module AbstractControllerTests end test "when a child controller does not have a layout, use the parent controller layout" do - result = WithStringChild.new.process(:index) - assert_equal "With String Hello string!", result.response_body + controller = WithStringChild.new + controller.process(:index) + assert_equal "With String Hello string!", controller.response_body end test "when a child controller has specified a layout, use that layout and not the parent controller layout" do - result = WithStringOverriddenChild.new.process(:index) - assert_equal "With Override Hello string!", result.response_body + controller = WithStringOverriddenChild.new + controller.process(:index) + assert_equal "With Override Hello string!", controller.response_body end test "when a child controller has an implied layout, use that layout and not the parent controller layout" do - result = WithStringImpliedChild.new.process(:index) - assert_equal "With Implied Hello string!", result.response_body + controller = WithStringImpliedChild.new + controller.process(:index) + assert_equal "With Implied Hello string!", controller.response_body end test "when a child controller specifies layout nil, do not use the parent layout" do - result = WithNilChild.new.process(:index) - assert_equal "Hello string!", result.response_body + controller = WithNilChild.new + controller.process(:index) + assert_equal "Hello string!", controller.response_body end test "when a grandchild has no layout specified, the child has an implied layout, and the " \ "parent has specified a layout, use the child controller layout" do - result = WithChildOfImplied.new.process(:index) - assert_equal "With Implied Hello string!", result.response_body + controller = WithChildOfImplied.new + controller.process(:index) + assert_equal "With Implied Hello string!", controller.response_body end test "raises an exception when specifying layout true" do diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index b062a71442..07ba37c51c 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -6,6 +6,8 @@ $:.unshift(File.dirname(__FILE__) + '/lib') $:.unshift(File.dirname(__FILE__) + '/fixtures/helpers') $:.unshift(File.dirname(__FILE__) + '/fixtures/alternate_helpers') +ENV['TMPDIR'] = File.join(File.dirname(__FILE__), 'tmp') + ENV['new_base'] = "true" $stderr.puts "Running old tests on new_base" @@ -60,20 +62,33 @@ module ActionController } Base.session_store = nil + class << Routing + def possible_controllers + @@possible_controllers ||= [] + end + end + class Base include ActionController::Testing + + def self.inherited(klass) + name = klass.name.underscore.sub(/_controller$/, '') + ActionController::Routing.possible_controllers << name unless name.blank? + super + end end Base.view_paths = FIXTURE_LOAD_PATH class TestCase include TestProcess + setup do ActionController::Routing::Routes.draw do |map| map.connect ':controller/:action/:id' end end - + def assert_template(options = {}, message = nil) validate_request! diff --git a/actionpack/test/activerecord/active_record_store_test.rb b/actionpack/test/activerecord/active_record_store_test.rb index 47f8496181..a46ce7a0aa 100644 --- a/actionpack/test/activerecord/active_record_store_test.rb +++ b/actionpack/test/activerecord/active_record_store_test.rb @@ -1,12 +1,6 @@ require 'active_record_unit' class ActiveRecordStoreTest < ActionController::IntegrationTest - DispatcherApp = ActionController::Dispatcher.new - SessionApp = ActiveRecord::SessionStore.new(DispatcherApp, - :key => '_session_id') - SessionAppWithFixation = ActiveRecord::SessionStore.new(DispatcherApp, - :key => '_session_id', :cookie_only => false) - class TestController < ActionController::Base def no_session_access head :ok @@ -39,7 +33,7 @@ class ActiveRecordStoreTest < ActionController::IntegrationTest def setup ActiveRecord::SessionStore.session_class.create_table! - @integration_session = open_session(SessionApp) + reset_app! end def teardown @@ -138,9 +132,9 @@ class ActiveRecordStoreTest < ActionController::IntegrationTest end def test_allows_session_fixation - @integration_session = open_session(SessionAppWithFixation) - with_test_route_set do + reset_with_fixation! + get '/set_session_value' assert_response :success assert cookies['_session_id'] @@ -151,8 +145,7 @@ class ActiveRecordStoreTest < ActionController::IntegrationTest session_id = cookies['_session_id'] assert session_id - reset! - @integration_session = open_session(SessionAppWithFixation) + reset_with_fixation! get '/set_session_value', :_session_id => session_id, :foo => "baz" assert_response :success @@ -166,6 +159,16 @@ class ActiveRecordStoreTest < ActionController::IntegrationTest end private + def reset_app! + app = ActiveRecord::SessionStore.new(ActionController::Dispatcher.new, :key => '_session_id') + @integration_session = open_session(app) + end + + def reset_with_fixation! + app = ActiveRecord::SessionStore.new(ActionController::Dispatcher.new, :key => '_session_id', :cookie_only => false) + @integration_session = open_session(app) + end + def with_test_route_set with_routing do |set| set.draw do |map| diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb index ecbaba39d1..453812c128 100644 --- a/actionpack/test/controller/action_pack_assertions_test.rb +++ b/actionpack/test/controller/action_pack_assertions_test.rb @@ -182,18 +182,6 @@ end # a test case to exercise the new capabilities TestRequest & TestResponse class ActionPackAssertionsControllerTest < ActionController::TestCase - # let's get this party started - def setup - super - ActionController::Routing::Routes.reload - ActionController::Routing.use_controllers!(%w(action_pack_assertions admin/inner_module user content admin/user)) - end - - def teardown - super - ActionController::Routing::Routes.reload - end - # -- assertion-based testing ------------------------------------------------ def test_assert_tag_and_url_for diff --git a/actionpack/test/controller/base_test.rb b/actionpack/test/controller/base_test.rb index 8877057070..b97ceb4594 100644 --- a/actionpack/test/controller/base_test.rb +++ b/actionpack/test/controller/base_test.rb @@ -177,17 +177,17 @@ class DefaultUrlOptionsTest < ActionController::TestCase end def test_default_url_options_are_used_if_set - ActionController::Routing::Routes.draw do |map| - map.default_url_options 'default_url_options', :controller => 'default_url_options' - map.connect ':controller/:action/:id' - end + with_routing do |set| + set.draw do |map| + map.default_url_options 'default_url_options', :controller => 'default_url_options' + map.connect ':controller/:action/:id' + end - get :default_url_options_action # Make a dummy request so that the controller is initialized properly. + get :default_url_options_action # Make a dummy request so that the controller is initialized properly. - assert_equal 'http://www.override.com/default_url_options/new?bacon=chunky', @controller.url_for(:controller => 'default_url_options') - assert_equal 'http://www.override.com/default_url_options?bacon=chunky', @controller.send(:default_url_options_url) - ensure - ActionController::Routing::Routes.load! + assert_equal 'http://www.override.com/default_url_options/new?bacon=chunky', @controller.url_for(:controller => 'default_url_options') + assert_equal 'http://www.override.com/default_url_options?bacon=chunky', @controller.send(:default_url_options_url) + end end end @@ -206,15 +206,15 @@ class EmptyUrlOptionsTest < ActionController::TestCase end end -class EnsureNamedRoutesWorksTicket22BugTest < Test::Unit::TestCase +class EnsureNamedRoutesWorksTicket22BugTest < ActionController::TestCase def test_named_routes_still_work - ActionController::Routing::Routes.draw do |map| - map.resources :things - end - EmptyController.send :include, ActionController::UrlWriter + with_routing do |set| + set.draw do |map| + map.resources :things + end + EmptyController.send :include, ActionController::UrlWriter - assert_equal '/things', EmptyController.new.send(:things_path) - ensure - ActionController::Routing::Routes.load! + assert_equal '/things', EmptyController.new.send(:things_path) + end end end diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb index 68529cc8f7..82c790bc19 100644 --- a/actionpack/test/controller/caching_test.rb +++ b/actionpack/test/controller/caching_test.rb @@ -48,10 +48,8 @@ class PageCachingTest < ActionController::TestCase super ActionController::Base.perform_caching = true - ActionController::Routing::Routes.clear! - ActionController::Routing::Routes.draw do |map| - map.main '', :controller => 'posts' + map.main '', :controller => 'posts', :format => nil map.formatted_posts 'posts.:format', :controller => 'posts' map.resources :posts map.connect ':controller/:action/:id' @@ -72,7 +70,6 @@ class PageCachingTest < ActionController::TestCase def teardown FileUtils.rm_rf(File.dirname(FILE_STORE_PATH)) - ActionController::Routing::Routes.clear! ActionController::Base.perform_caching = false end @@ -536,7 +533,6 @@ class FragmentCachingTest < ActionController::TestCase @controller.params = @params @controller.request = @request @controller.response = @response - @controller.send(:initialize_current_url) @controller.send(:initialize_template_class, @response) @controller.send(:assign_shortcuts, @request, @response) end diff --git a/actionpack/test/controller/content_type_test.rb b/actionpack/test/controller/content_type_test.rb index 511788aec8..c249788c67 100644 --- a/actionpack/test/controller/content_type_test.rb +++ b/actionpack/test/controller/content_type_test.rb @@ -46,7 +46,7 @@ class ContentTypeController < ActionController::Base def render_default_content_types_for_respond_to respond_to do |format| format.html { render :text => "hello world!" } - format.xml { render :action => "render_default_content_types_for_respond_to.rhtml" } + format.xml { render :action => "render_default_content_types_for_respond_to" } format.js { render :text => "hello world!" } format.rss { render :text => "hello world!", :content_type => Mime::XML } end diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb index 8319b5c573..93a815adae 100644 --- a/actionpack/test/controller/mime_responds_test.rb +++ b/actionpack/test/controller/mime_responds_test.rb @@ -79,29 +79,20 @@ class RespondToController < ActionController::Base end end - def custom_constant_handling - Mime::Type.register("text/x-mobile", :mobile) + Mime::Type.register("text/x-mobile", :mobile) + def custom_constant_handling respond_to do |type| type.html { render :text => "HTML" } type.mobile { render :text => "Mobile" } end - ensure - Mime::SET.delete(:mobile) - Mime.module_eval { remove_const :MOBILE if const_defined?(:MOBILE) } end def custom_constant_handling_without_block - Mime::Type.register("text/x-mobile", :mobile) - respond_to do |type| type.html { render :text => "HTML" } type.mobile end - - ensure - Mime::SET.delete(:mobile) - Mime.module_eval { remove_const :MOBILE if const_defined?(:MOBILE) } end def handle_any @@ -125,32 +116,24 @@ class RespondToController < ActionController::Base end end + Mime::Type.register_alias("text/html", :iphone) + def iphone_with_html_response_type - Mime::Type.register_alias("text/html", :iphone) request.format = :iphone if request.env["HTTP_ACCEPT"] == "text/iphone" respond_to do |type| type.html { @type = "Firefox" } type.iphone { @type = "iPhone" } end - - ensure - Mime::SET.delete(:iphone) - Mime.module_eval { remove_const :IPHONE if const_defined?(:IPHONE) } end def iphone_with_html_response_type_without_layout - Mime::Type.register_alias("text/html", :iphone) request.format = "iphone" if request.env["HTTP_ACCEPT"] == "text/iphone" respond_to do |type| type.html { @type = "Firefox"; render :action => "iphone_with_html_response_type" } type.iphone { @type = "iPhone" ; render :action => "iphone_with_html_response_type" } end - - ensure - Mime::SET.delete(:iphone) - Mime.module_eval { remove_const :IPHONE if const_defined?(:IPHONE) } end def rescue_action(e) @@ -213,18 +196,20 @@ class RespondToControllerTest < ActionController::TestCase def test_js_or_html @request.accept = "text/javascript, text/html" - get :js_or_html + xhr :get, :js_or_html assert_equal 'JS', @response.body - get :html_or_xml + @request.accept = "text/javascript, text/html" + xhr :get, :html_or_xml assert_equal 'HTML', @response.body - get :just_xml + @request.accept = "text/javascript, text/html" + xhr :get, :just_xml assert_response 406 end def test_json_or_yaml - get :json_or_yaml + xhr :get, :json_or_yaml assert_equal 'JSON', @response.body get :json_or_yaml, :format => 'json' @@ -246,13 +231,13 @@ class RespondToControllerTest < ActionController::TestCase def test_js_or_anything @request.accept = "text/javascript, */*" - get :js_or_html + xhr :get, :js_or_html assert_equal 'JS', @response.body - get :html_or_xml + xhr :get, :html_or_xml assert_equal 'HTML', @response.body - get :just_xml + xhr :get, :just_xml assert_equal 'XML', @response.body end @@ -291,14 +276,16 @@ class RespondToControllerTest < ActionController::TestCase end def test_with_atom_content_type + @request.accept = "" @request.env["CONTENT_TYPE"] = "application/atom+xml" - get :made_for_content_type + xhr :get, :made_for_content_type assert_equal "ATOM", @response.body end def test_with_rss_content_type + @request.accept = "" @request.env["CONTENT_TYPE"] = "application/rss+xml" - get :made_for_content_type + xhr :get, :made_for_content_type assert_equal "RSS", @response.body end @@ -497,8 +484,12 @@ class RespondWithController < ActionController::Base respond_with(Customer.new("david", 13)) end + def using_resource_with_collection + respond_with([Customer.new("david", 13), Customer.new("jamis", 9)]) + end + def using_resource_with_parent - respond_with([Quiz::Store.new("developer?", 11), Customer.new("david", 13)]) + respond_with(Quiz::Store.new("developer?", 11), Customer.new("david", 13)) end def using_resource_with_status_and_location @@ -506,7 +497,7 @@ class RespondWithController < ActionController::Base end def using_resource_with_responder - responder = proc { |c, r, o| c.render :text => "Resource name is #{r.name}" } + responder = proc { |c, r, o| c.render :text => "Resource name is #{r.first.name}" } respond_with(Customer.new("david", 13), :responder => responder) end @@ -540,6 +531,7 @@ class RespondWithControllerTest < ActionController::TestCase ActionController::Routing::Routes.draw do |map| map.resources :customers map.resources :quiz_stores, :has_many => :customers + map.connect ":controller/:action/:id" end end @@ -592,7 +584,7 @@ class RespondWithControllerTest < ActionController::TestCase @request.accept = "application/xml" get :using_resource assert_equal "application/xml", @response.content_type - assert_equal "XML", @response.body + assert_equal "<name>david</name>", @response.body @request.accept = "application/json" assert_raise ActionView::MissingTemplate do @@ -622,7 +614,7 @@ class RespondWithControllerTest < ActionController::TestCase post :using_resource assert_equal "application/xml", @response.content_type assert_equal 201, @response.status - assert_equal "XML", @response.body + assert_equal "<name>david</name>", @response.body assert_equal "http://www.example.com/customers/13", @response.location errors = { :name => :invalid } @@ -689,7 +681,7 @@ class RespondWithControllerTest < ActionController::TestCase get :using_resource_with_parent assert_equal "application/xml", @response.content_type assert_equal 200, @response.status - assert_equal "XML", @response.body + assert_equal "<name>david</name>", @response.body end def test_using_resource_with_parent_for_post @@ -698,7 +690,7 @@ class RespondWithControllerTest < ActionController::TestCase post :using_resource_with_parent assert_equal "application/xml", @response.content_type assert_equal 201, @response.status - assert_equal "XML", @response.body + assert_equal "<name>david</name>", @response.body assert_equal "http://www.example.com/quiz_stores/11/customers/13", @response.location errors = { :name => :invalid } @@ -710,6 +702,15 @@ class RespondWithControllerTest < ActionController::TestCase assert_nil @response.location end + def test_using_resource_with_collection + @request.accept = "application/xml" + 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 + end + def test_clear_respond_to @controller = InheritedRespondWithController.new @request.accept = "text/html" @@ -722,7 +723,14 @@ class RespondWithControllerTest < ActionController::TestCase @request.accept = "*/*" get :index assert_equal "application/xml", @response.content_type - assert_equal "XML", @response.body + assert_equal "<name>david</name>", @response.body + end + + def test_block_inside_respond_with_is_rendered + @controller = InheritedRespondWithController.new + @request.accept = "application/json" + get :index + assert_equal "JSON", @response.body end def test_no_double_render_is_raised @@ -782,12 +790,8 @@ class PostController < AbstractPostController protected def with_iphone - Mime::Type.register_alias("text/html", :iphone) request.format = "iphone" if request.env["HTTP_ACCEPT"] == "text/iphone" yield - ensure - Mime::SET.delete(:iphone) - Mime.module_eval { remove_const :IPHONE if const_defined?(:IPHONE) } end end diff --git a/actionpack/test/controller/redirect_test.rb b/actionpack/test/controller/redirect_test.rb index 7755af592d..ea278fd8f0 100644 --- a/actionpack/test/controller/redirect_test.rb +++ b/actionpack/test/controller/redirect_test.rb @@ -231,18 +231,20 @@ class RedirectTest < ActionController::TestCase end def test_redirect_to_record - ActionController::Routing::Routes.draw do |map| - map.resources :workshops - map.connect ':controller/:action/:id' + with_routing do |set| + set.draw do |map| + map.resources :workshops + map.connect ':controller/:action/:id' + end + + get :redirect_to_existing_record + assert_equal "http://test.host/workshops/5", redirect_to_url + assert_redirected_to Workshop.new(5, false) + + get :redirect_to_new_record + assert_equal "http://test.host/workshops", redirect_to_url + assert_redirected_to Workshop.new(5, true) end - - get :redirect_to_existing_record - assert_equal "http://test.host/workshops/5", redirect_to_url - assert_redirected_to Workshop.new(5, false) - - get :redirect_to_new_record - assert_equal "http://test.host/workshops", redirect_to_url - assert_redirected_to Workshop.new(5, true) end def test_redirect_to_nil diff --git a/actionpack/test/controller/render_js_test.rb b/actionpack/test/controller/render_js_test.rb index d02fd3fd4c..bc850de733 100644 --- a/actionpack/test/controller/render_js_test.rb +++ b/actionpack/test/controller/render_js_test.rb @@ -13,7 +13,7 @@ class TestController < ActionController::Base # let's just rely on the template end - def partial + def show_partial render :partial => 'partial' end end @@ -33,7 +33,7 @@ class RenderTest < ActionController::TestCase end def test_should_render_js_partial - xhr :get, :partial, :format => 'js' + xhr :get, :show_partial, :format => 'js' assert_equal 'partial js', @response.body - end + end end
\ No newline at end of file diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb index 0c0599679c..abcc8bf384 100644 --- a/actionpack/test/controller/render_test.rb +++ b/actionpack/test/controller/render_test.rb @@ -486,10 +486,6 @@ class TestController < ActionController::Base render :action => "using_layout_around_block" end - def render_using_layout_around_block_with_args - render :action => "using_layout_around_block_with_args" - end - def render_using_layout_around_block_in_main_layout_and_within_content_for_layout render :action => "using_layout_around_block", :layout => "layouts/block_with_layout" end @@ -1090,15 +1086,17 @@ class RenderTest < ActionController::TestCase end def test_head_with_location_object - ActionController::Routing::Routes.draw do |map| - map.resources :customers - map.connect ':controller/:action/:id' - end + with_routing do |set| + set.draw do |map| + map.resources :customers + map.connect ':controller/:action/:id' + end - get :head_with_location_object - assert @response.body.blank? - assert_equal "http://www.nextangle.com/customers/1", @response.headers["Location"] - assert_response :ok + get :head_with_location_object + assert @response.body.blank? + assert_equal "http://www.nextangle.com/customers/1", @response.headers["Location"] + assert_response :ok + end end def test_head_with_custom_header @@ -1161,11 +1159,6 @@ class RenderTest < ActionController::TestCase assert_equal "Before (Anthony)\nInside from first block in layout\nAfter\nBefore (David)\nInside from block\nAfter\nBefore (Ramm)\nInside from second block in layout\nAfter\n", @response.body end - def test_using_layout_around_block_with_args - get :render_using_layout_around_block_with_args - assert_equal "Before\narg1arg2\nAfter", @response.body - end - def test_partial_only get :partial_only assert_equal "only partial", @response.body diff --git a/actionpack/test/controller/render_xml_test.rb b/actionpack/test/controller/render_xml_test.rb index 139f55d8bd..e96e8a4d57 100644 --- a/actionpack/test/controller/render_xml_test.rb +++ b/actionpack/test/controller/render_xml_test.rb @@ -55,13 +55,15 @@ class RenderTest < ActionController::TestCase end def test_rendering_with_object_location_should_set_header_with_url_for - ActionController::Routing::Routes.draw do |map| - map.resources :customers - map.connect ':controller/:action/:id' - end + with_routing do |set| + set.draw do |map| + map.resources :customers + map.connect ':controller/:action/:id' + end - get :render_with_object_location - assert_equal "http://www.nextangle.com/customers/1", @response.headers["Location"] + get :render_with_object_location + assert_equal "http://www.nextangle.com/customers/1", @response.headers["Location"] + end end def test_should_render_formatted_xml_erb_template diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb index 83925ed4db..7111796f8d 100644 --- a/actionpack/test/controller/request_forgery_protection_test.rb +++ b/actionpack/test/controller/request_forgery_protection_test.rb @@ -1,10 +1,6 @@ require 'abstract_unit' require 'digest/sha1' -ActionController::Routing::Routes.draw do |map| - map.connect ':controller/:action/:id' -end - # common controller actions module RequestForgeryProtectionActions def index @@ -50,7 +46,7 @@ module RequestForgeryProtectionTests def teardown ActionController::Base.request_forgery_protection_token = nil end - + def test_should_render_form_with_token_tag get :index diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb index 30ab110ef7..0b639e363d 100644 --- a/actionpack/test/controller/resources_test.rb +++ b/actionpack/test/controller/resources_test.rb @@ -76,6 +76,50 @@ class ResourcesTest < ActionController::TestCase end 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' } + + with_restful_routing :messages, + :collection => collection_methods, + :member => member_methods, + :path_names => path_names do + + assert_restful_routes_for :messages, + :collection => collection_methods, + :member => member_methods, + :path_names => path_names do |options| + member_methods.each do |action, method| + assert_recognizes(options.merge(:action => action.to_s, :id => '1'), + :path => "/messages/1/#{path_names[action] || action}", + :method => method) + end + + collection_methods.each do |action, method| + assert_recognizes(options.merge(:action => action), + :path => "/messages/#{path_names[action] || action}", + :method => method) + end + end + + assert_restful_named_routes_for :messages, + :collection => collection_methods, + :member => member_methods, + :path_names => path_names do |options| + + collection_methods.keys.each do |action| + assert_named_route "/messages/#{path_names[action] || action}", "#{action}_messages_path", :action => action + end + + member_methods.keys.each do |action| + assert_named_route "/messages/1/#{path_names[action] || action}", "#{action}_message_path", :action => action, :id => "1" + end + + end + end + end + def test_override_paths_for_default_restful_actions resource = ActionController::Resources::Resource.new(:messages, :path_names => {:new => 'nuevo', :edit => 'editar'}) diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb index 5f9ae6292c..d20684296f 100644 --- a/actionpack/test/controller/routing_test.rb +++ b/actionpack/test/controller/routing_test.rb @@ -9,7 +9,6 @@ class MilestonesController < ActionController::Base def rescue_action(e) raise e end end -RunTimeTests = ARGV.include? 'time' ROUTING = ActionController::Routing class ROUTING::RouteBuilder @@ -45,11 +44,11 @@ class UriReservedCharactersRoutingTest < Test::Unit::TestCase end def test_route_recognition_unescapes_path_components - options = { :controller => "controller", + options = { :controller => "content", :action => "act#{@segment}ion", :variable => "var#{@segment}iable", :additional => ["add#{@segment}itional-1", "add#{@segment}itional-2"] } - assert_equal options, @set.recognize_path("/controller/act#{@escaped}ion/var#{@escaped}iable/add#{@escaped}itional-1/add#{@escaped}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 @@ -60,644 +59,7 @@ class UriReservedCharactersRoutingTest < Test::Unit::TestCase end end -class SegmentTest < Test::Unit::TestCase - def test_first_segment_should_interpolate_for_structure - s = ROUTING::Segment.new - def s.interpolation_statement(array) 'hello' end - assert_equal 'hello', s.continue_string_structure([]) - end - - def test_interpolation_statement - s = ROUTING::StaticSegment.new("Hello") - assert_equal "Hello", eval(s.interpolation_statement([])) - assert_equal "HelloHello", eval(s.interpolation_statement([s])) - - s2 = ROUTING::StaticSegment.new("-") - assert_equal "Hello-Hello", eval(s.interpolation_statement([s, s2])) - - s3 = ROUTING::StaticSegment.new("World") - assert_equal "Hello-World", eval(s3.interpolation_statement([s, s2])) - end -end - -class StaticSegmentTest < Test::Unit::TestCase - def test_interpolation_chunk_should_respect_raw - s = ROUTING::StaticSegment.new('Hello World') - assert !s.raw? - assert_equal 'Hello%20World', s.interpolation_chunk - - s = ROUTING::StaticSegment.new('Hello World', :raw => true) - assert s.raw? - assert_equal 'Hello World', s.interpolation_chunk - end - - def test_value_should_not_be_double_unescaped - s = ROUTING::StaticSegment.new('%D0%9A%D0%B0%D1%80%D1%82%D0%B0') # Карта - assert_equal '%D0%9A%D0%B0%D1%80%D1%82%D0%B0', s.interpolation_chunk - end - - def test_regexp_chunk_should_escape_specials - s = ROUTING::StaticSegment.new('Hello*World') - assert_equal 'Hello\*World', s.regexp_chunk - - s = ROUTING::StaticSegment.new('HelloWorld') - assert_equal 'HelloWorld', s.regexp_chunk - end - - def test_regexp_chunk_should_add_question_mark_for_optionals - s = ROUTING::StaticSegment.new("/", :optional => true) - assert_equal "/?", s.regexp_chunk - - s = ROUTING::StaticSegment.new("hello", :optional => true) - assert_equal "(?:hello)?", s.regexp_chunk - end -end - -class DynamicSegmentTest < Test::Unit::TestCase - def segment(options = {}) - unless @segment - @segment = ROUTING::DynamicSegment.new(:a, options) - end - @segment - end - - def test_extract_value - s = ROUTING::DynamicSegment.new(:a) - - hash = {:a => '10', :b => '20'} - assert_equal '10', eval(s.extract_value) - - hash = {:b => '20'} - assert_equal nil, eval(s.extract_value) - - s.default = '20' - assert_equal '20', eval(s.extract_value) - end - - def test_default_local_name - assert_equal 'a_value', segment.local_name, - "Unexpected name -- all value_check tests will fail!" - end - - def test_presence_value_check - a_value = 10 - assert eval(segment.value_check) - end - - def test_regexp_value_check_rejects_nil - segment = segment(:regexp => /\d+/) - - a_value = nil - assert !eval(segment.value_check) - end - - def test_optional_regexp_value_check_should_accept_nil - segment = segment(:regexp => /\d+/, :optional => true) - - a_value = nil - assert eval(segment.value_check) - end - - def test_regexp_value_check_rejects_no_match - segment = segment(:regexp => /\d+/) - - a_value = "Hello20World" - assert !eval(segment.value_check) - - a_value = "20Hi" - assert !eval(segment.value_check) - end - - def test_regexp_value_check_accepts_match - segment = segment(:regexp => /\d+/) - a_value = "30" - assert eval(segment.value_check) - end - - def test_value_check_fails_on_nil - a_value = nil - assert ! eval(segment.value_check) - end - - def test_optional_value_needs_no_check - segment = segment(:optional => true) - - a_value = nil - assert_equal nil, segment.value_check - end - - def test_regexp_value_check_should_accept_match_with_default - segment = segment(:regexp => /\d+/, :default => '200') - - a_value = '100' - assert eval(segment.value_check) - end - - def test_expiry_should_not_trigger_once_expired - expired = true - hash = merged = {:a => 2, :b => 3} - options = {:b => 3} - expire_on = Hash.new { raise 'No!!!' } - - eval(segment.expiry_statement) - rescue RuntimeError - flunk "Expiry check should not have occurred!" - end - - def test_expiry_should_occur_according_to_expire_on - expired = false - hash = merged = {:a => 2, :b => 3} - options = {:b => 3} - - expire_on = {:b => true, :a => false} - eval(segment.expiry_statement) - assert !expired - assert_equal({:a => 2, :b => 3}, hash) - - expire_on = {:b => true, :a => true} - eval(segment.expiry_statement) - assert expired - assert_equal({:b => 3}, hash) - end - - def test_extraction_code_should_return_on_nil - hash = merged = {:b => 3} - options = {:b => 3} - a_value = nil - - # Local jump because of return inside eval. - assert_raise(LocalJumpError) { eval(segment.extraction_code) } - end - - def test_extraction_code_should_return_on_mismatch - segment = segment(:regexp => /\d+/) - hash = merged = {:a => 'Hi', :b => '3'} - options = {:b => '3'} - a_value = nil - - # Local jump because of return inside eval. - assert_raise(LocalJumpError) { eval(segment.extraction_code) } - end - - def test_extraction_code_should_accept_value_and_set_local - hash = merged = {:a => 'Hi', :b => '3'} - options = {:b => '3'} - a_value = nil - expired = true - - eval(segment.extraction_code) - assert_equal 'Hi', a_value - end - - def test_extraction_should_work_without_value_check - segment.default = 'hi' - hash = merged = {:b => '3'} - options = {:b => '3'} - a_value = nil - expired = true - - eval(segment.extraction_code) - assert_equal 'hi', a_value - end - - def test_extraction_code_should_perform_expiry - expired = false - hash = merged = {:a => 'Hi', :b => '3'} - options = {:b => '3'} - expire_on = {:a => true} - a_value = nil - - eval(segment.extraction_code) - assert_equal 'Hi', a_value - assert expired - assert_equal options, hash - end - - def test_interpolation_chunk_should_replace_value - a_value = 'Hi' - assert_equal a_value, eval(%("#{segment.interpolation_chunk}")) - end - - def test_interpolation_chunk_should_accept_nil - a_value = nil - assert_equal '', eval(%("#{segment.interpolation_chunk('a_value')}")) - end - - def test_value_regexp_should_be_nil_without_regexp - assert_equal nil, segment.value_regexp - end - - def test_value_regexp_should_match_exacly - segment = segment(:regexp => /\d+/) - assert_no_match segment.value_regexp, "Hello 10 World" - assert_no_match segment.value_regexp, "Hello 10" - assert_no_match segment.value_regexp, "10 World" - assert_match segment.value_regexp, "10" - end - - def test_regexp_chunk_should_return_string - segment = segment(:regexp => /\d+/) - assert_kind_of String, segment.regexp_chunk - end - - def test_build_pattern_non_optional_with_no_captures - # Non optional - a_segment = ROUTING::DynamicSegment.new(nil, :regexp => /\d+/) - assert_equal "(\\d+)stuff", a_segment.build_pattern('stuff') - end - - def test_build_pattern_non_optional_with_captures - # Non optional - a_segment = ROUTING::DynamicSegment.new(nil, :regexp => /(\d+)(.*?)/) - assert_equal "((\\d+)(.*?))stuff", a_segment.build_pattern('stuff') - end - - def test_optionality_implied - a_segment = ROUTING::DynamicSegment.new(:id) - assert a_segment.optionality_implied? - - a_segment = ROUTING::DynamicSegment.new(:action) - assert a_segment.optionality_implied? - end - - def test_modifiers_must_be_handled_sensibly - a_segment = ROUTING::DynamicSegment.new(nil, :regexp => /david|jamis/i) - assert_equal "((?i-mx:david|jamis))stuff", a_segment.build_pattern('stuff') - a_segment = ROUTING::DynamicSegment.new(nil, :regexp => /david|jamis/x) - assert_equal "((?x-mi:david|jamis))stuff", a_segment.build_pattern('stuff') - a_segment = ROUTING::DynamicSegment.new(nil, :regexp => /david|jamis/) - assert_equal "(david|jamis)stuff", a_segment.build_pattern('stuff') - end -end - -class ControllerSegmentTest < Test::Unit::TestCase - def test_regexp_should_only_match_possible_controllers - ActionController::Routing.with_controllers %w(admin/accounts admin/users account pages) do - cs = ROUTING::ControllerSegment.new :controller - regexp = %r{\A#{cs.regexp_chunk}\Z} - - ActionController::Routing.possible_controllers.each do |name| - assert_match regexp, name - assert_no_match regexp, "#{name}_fake" - - match = regexp.match name - assert_equal name, match[1] - end - end - end -end - -class PathSegmentTest < Test::Unit::TestCase - def segment(options = {}) - unless @segment - @segment = ROUTING::PathSegment.new(:path, options) - end - @segment - end - - def test_regexp_chunk_should_return_string - segment = segment(:regexp => /[a-z]+/) - assert_kind_of String, segment.regexp_chunk - end - - def test_regexp_chunk_should_be_wrapped_with_parenthesis - segment = segment(:regexp => /[a-z]+/) - assert_equal "([a-z]+)", segment.regexp_chunk - end - - def test_regexp_chunk_should_respect_options - segment = segment(:regexp => /[a-z]+/i) - assert_equal "((?i-mx:[a-z]+))", segment.regexp_chunk - end -end - -class RouteBuilderTest < Test::Unit::TestCase - def builder - @builder ||= ROUTING::RouteBuilder.new - end - - def build(path, options) - builder.build(path, options) - end - - def test_options_should_not_be_modified - requirements1 = { :id => /\w+/, :controller => /(?:[a-z](?:-?[a-z]+)*)/ } - requirements2 = requirements1.dup - - assert_equal requirements1, requirements2 - - with_options(:controller => 'folder', - :requirements => requirements2) do |m| - m.build 'folders/new', :action => 'new' - end - - assert_equal requirements1, requirements2 - end - - def test_segment_for_static - segment, rest = builder.segment_for 'ulysses' - assert_equal '', rest - assert_kind_of ROUTING::StaticSegment, segment - assert_equal 'ulysses', segment.value - end - - def test_segment_for_action - segment, rest = builder.segment_for ':action' - assert_equal '', rest - assert_kind_of ROUTING::DynamicSegment, segment - assert_equal :action, segment.key - assert_equal 'index', segment.default - end - - def test_segment_for_dynamic - segment, rest = builder.segment_for ':login' - assert_equal '', rest - assert_kind_of ROUTING::DynamicSegment, segment - assert_equal :login, segment.key - assert_equal nil, segment.default - assert ! segment.optional? - end - - def test_segment_for_with_rest - segment, rest = builder.segment_for ':login/:action' - assert_equal :login, segment.key - assert_equal '/:action', rest - segment, rest = builder.segment_for rest - assert_equal '/', segment.value - assert_equal ':action', rest - segment, rest = builder.segment_for rest - assert_equal :action, segment.key - assert_equal '', rest - end - - def test_segments_for - segments = builder.segments_for_route_path '/:controller/:action/:id' - - assert_kind_of ROUTING::DividerSegment, segments[0] - assert_equal '/', segments[2].value - - assert_kind_of ROUTING::DynamicSegment, segments[1] - assert_equal :controller, segments[1].key - - assert_kind_of ROUTING::DividerSegment, segments[2] - assert_equal '/', segments[2].value - - assert_kind_of ROUTING::DynamicSegment, segments[3] - assert_equal :action, segments[3].key - - assert_kind_of ROUTING::DividerSegment, segments[4] - assert_equal '/', segments[4].value - - assert_kind_of ROUTING::DynamicSegment, segments[5] - assert_equal :id, segments[5].key - end - - def test_segment_for_action - s, r = builder.segment_for(':action/something/else') - assert_equal '/something/else', r - assert_equal :action, s.key - end - - def test_action_default_should_not_trigger_on_prefix - s, r = builder.segment_for ':action_name/something/else' - assert_equal '/something/else', r - assert_equal :action_name, s.key - assert_equal nil, s.default - end - - def test_divide_route_options - segments = builder.segments_for_route_path '/cars/:action/:person/:car/' - defaults, requirements = builder.divide_route_options(segments, - :action => 'buy', :person => /\w+/, :car => /\w+/, - :defaults => {:person => nil, :car => nil} - ) - - assert_equal({:action => 'buy', :person => nil, :car => nil}, defaults) - assert_equal({:person => /\w+/, :car => /\w+/}, requirements) - end - - def test_assign_route_options - segments = builder.segments_for_route_path '/cars/:action/:person/:car/' - defaults = {:action => 'buy', :person => nil, :car => nil} - requirements = {:person => /\w+/, :car => /\w+/} - - route_requirements = builder.assign_route_options(segments, defaults, requirements) - assert_equal({}, route_requirements) - - assert_equal :action, segments[3].key - assert_equal 'buy', segments[3].default - - assert_equal :person, segments[5].key - assert_equal %r/\w+/, segments[5].regexp - assert segments[5].optional? - - assert_equal :car, segments[7].key - assert_equal %r/\w+/, segments[7].regexp - assert segments[7].optional? - end - - def test_assign_route_options_with_anchor_chars - segments = builder.segments_for_route_path '/cars/:action/:person/:car/' - defaults = {:action => 'buy', :person => nil, :car => nil} - requirements = {:person => /\w+/, :car => /^\w+$/} - - assert_raise ArgumentError do - route_requirements = builder.assign_route_options(segments, defaults, requirements) - end - - requirements[:car] = /[^\/]+/ - route_requirements = builder.assign_route_options(segments, defaults, requirements) - end - - def test_optional_segments_preceding_required_segments - segments = builder.segments_for_route_path '/cars/:action/:person/:car/' - defaults = {:action => 'buy', :person => nil, :car => "model-t"} - assert builder.assign_route_options(segments, defaults, {}).empty? - - 0.upto(1) { |i| assert !segments[i].optional?, "segment #{i} is optional and it shouldn't be" } - assert segments[2].optional? - - assert_equal nil, builder.warn_output # should only warn on the :person segment - end - - def test_segmentation_of_dot_path - segments = builder.segments_for_route_path '/books/:action.rss' - assert builder.assign_route_options(segments, {}, {}).empty? - assert_equal 6, segments.length # "/", "books", "/", ":action", ".", "rss" - assert !segments.any? { |seg| seg.optional? } - end - - def test_segmentation_of_dynamic_dot_path - segments = builder.segments_for_route_path '/books/:action.:format' - assert builder.assign_route_options(segments, {}, {}).empty? - assert_equal 6, segments.length # "/", "books", "/", ":action", ".", ":format" - assert !segments.any? { |seg| seg.optional? } - assert_kind_of ROUTING::DynamicSegment, segments.last - end - - def test_assignment_of_default_options - segments = builder.segments_for_route_path '/:controller/:action/:id/' - action, id = segments[-4], segments[-2] - - assert_equal :action, action.key - assert_equal :id, id.key - assert ! action.optional? - assert ! id.optional? - - builder.assign_default_route_options(segments) - - assert_equal 'index', action.default - assert action.optional? - assert id.optional? - end - - def test_assignment_of_default_options_respects_existing_defaults - segments = builder.segments_for_route_path '/:controller/:action/:id/' - action, id = segments[-4], segments[-2] - - assert_equal :action, action.key - assert_equal :id, id.key - action.default = 'show' - action.is_optional = true - - id.default = 'Welcome' - id.is_optional = true - - builder.assign_default_route_options(segments) - - assert_equal 'show', action.default - assert action.optional? - assert_equal 'Welcome', id.default - assert id.optional? - end - - def test_assignment_of_default_options_respects_regexps - segments = builder.segments_for_route_path '/:controller/:action/:id/' - action = segments[-4] - - assert_equal :action, action.key - segments[-4] = ROUTING::DynamicSegment.new(:action, :regexp => /show|in/) - - builder.assign_default_route_options(segments) - - assert_equal nil, action.default - assert ! action.optional? - end - - def test_assignment_of_is_optional_when_default - segments = builder.segments_for_route_path '/books/:action.rss' - assert_equal segments[3].key, :action - segments[3].default = 'changes' - builder.ensure_required_segments(segments) - assert ! segments[3].optional? - end - - def test_is_optional_is_assigned_to_default_segments - segments = builder.segments_for_route_path '/books/:action' - builder.assign_route_options(segments, {:action => 'index'}, {}) - - assert_equal segments[3].key, :action - assert segments[3].optional? - assert_kind_of ROUTING::DividerSegment, segments[2] - assert segments[2].optional? - end - - # XXX is optional not being set right? - # /blah/:defaulted_segment <-- is the second slash optional? it should be. - - def test_route_build - ActionController::Routing.with_controllers %w(users pages) do - r = builder.build '/:controller/:action/:id/', :action => nil - - [0, 2, 4].each do |i| - assert_kind_of ROUTING::DividerSegment, r.segments[i] - assert_equal '/', r.segments[i].value - assert r.segments[i].optional? if i > 1 - end - - assert_kind_of ROUTING::DynamicSegment, r.segments[1] - assert_equal :controller, r.segments[1].key - assert_equal nil, r.segments[1].default - - assert_kind_of ROUTING::DynamicSegment, r.segments[3] - assert_equal :action, r.segments[3].key - assert_equal 'index', r.segments[3].default - - assert_kind_of ROUTING::DynamicSegment, r.segments[5] - assert_equal :id, r.segments[5].key - assert r.segments[5].optional? - end - end - - def test_slashes_are_implied - routes = [ - builder.build('/:controller/:action/:id/', :action => nil), - builder.build('/:controller/:action/:id', :action => nil), - builder.build(':controller/:action/:id', :action => nil), - builder.build('/:controller/:action/:id/', :action => nil) - ] - expected = routes.first.segments.length - routes.each_with_index do |route, i| - found = route.segments.length - assert_equal expected, found, "Route #{i + 1} has #{found} segments, expected #{expected}" - end - end -end - class RoutingTest < Test::Unit::TestCase - def test_possible_controllers - true_controller_paths = ActionController::Routing.controller_paths - - ActionController::Routing.use_controllers! nil - - Object.send(:remove_const, :RAILS_ROOT) if defined?(::RAILS_ROOT) - Object.const_set(:RAILS_ROOT, File.dirname(__FILE__) + '/controller_fixtures') - - ActionController::Routing.controller_paths = [ - RAILS_ROOT, RAILS_ROOT + '/app/controllers', RAILS_ROOT + '/vendor/plugins/bad_plugin/lib' - ] - - assert_equal ["admin/user", "plugin", "user"], ActionController::Routing.possible_controllers.sort - ensure - if true_controller_paths - ActionController::Routing.controller_paths = true_controller_paths - end - ActionController::Routing.use_controllers! nil - Object.send(:remove_const, :RAILS_ROOT) rescue nil - end - - def test_possible_controllers_are_reset_on_each_load - true_possible_controllers = ActionController::Routing.possible_controllers - true_controller_paths = ActionController::Routing.controller_paths - - ActionController::Routing.use_controllers! nil - root = File.dirname(__FILE__) + '/controller_fixtures' - - ActionController::Routing.controller_paths = [] - assert_equal [], ActionController::Routing.possible_controllers - - ActionController::Routing.controller_paths = [ - root, root + '/app/controllers', root + '/vendor/plugins/bad_plugin/lib' - ] - ActionController::Routing::Routes.load! - - assert_equal ["admin/user", "plugin", "user"], ActionController::Routing.possible_controllers.sort - ensure - ActionController::Routing.controller_paths = true_controller_paths - ActionController::Routing.use_controllers! true_possible_controllers - Object.send(:remove_const, :RAILS_ROOT) rescue nil - - ActionController::Routing::Routes.clear! - ActionController::Routing::Routes.load_routes! - end - - def test_with_controllers - c = %w(admin/accounts admin/users account pages) - ActionController::Routing.with_controllers c do - assert_equal c, ActionController::Routing.possible_controllers - end - end - def test_normalize_unix_paths load_paths = %w(. config/../app/controllers config/../app//helpers script/../config/../vendor/rails/actionpack/lib vendor/rails/railties/builtin/rails_info app/models lib script/../config/../foo/bar/../../app/models .foo/../.bar foo.bar/../config) paths = ActionController::Routing.normalize_paths(load_paths) @@ -759,7 +121,7 @@ class LegacyRouteSetTests < Test::Unit::TestCase ActionController::Routing.use_controllers! %w(content admin/user admin/news_feed) end - + def teardown @rs.clear! end @@ -815,52 +177,6 @@ class LegacyRouteSetTests < Test::Unit::TestCase map.resources :pages map.connect ':controller/:action/:id' } - n = 1000 - if RunTimeTests - GC.start - rectime = Benchmark.realtime do - n.times do - rs.recognize_path("/videos/1234567", {:method => :get}) - rs.recognize_path("/videos/1234567/abuse", {:method => :get}) - rs.recognize_path("/users/1234567/settings", {:method => :get}) - rs.recognize_path("/channels/1234567", {:method => :get}) - rs.recognize_path("/session/new", {:method => :get}) - rs.recognize_path("/admin/user/show/10", {:method => :get}) - end - end - puts "\n\nRecognition (#{rs.routes.size} routes):" - per_url = rectime / (n * 6) - puts "#{per_url * 1000} ms/url" - puts "#{1 / per_url} url/s\n\n" - end - end - - def test_time_generation - n = 5000 - if RunTimeTests - GC.start - pairs = [ - [{:controller => 'content', :action => 'index'}, {:controller => 'content', :action => 'show'}], - [{:controller => 'content'}, {:controller => 'content', :action => 'index'}], - [{:controller => 'content', :action => 'list'}, {:controller => 'content', :action => 'index'}], - [{:controller => 'content', :action => 'show', :id => '10'}, {:controller => 'content', :action => 'list'}], - [{:controller => 'admin/user', :action => 'index'}, {:controller => 'admin/user', :action => 'show'}], - [{:controller => 'admin/user'}, {:controller => 'admin/user', :action => 'index'}], - [{:controller => 'admin/user', :action => 'list'}, {:controller => 'admin/user', :action => 'index'}], - [{:controller => 'admin/user', :action => 'show', :id => '10'}, {:controller => 'admin/user', :action => 'list'}], - ] - p = nil - gentime = Benchmark.realtime do - n.times do - pairs.each {|(a, b)| rs.generate(a, b)} - end - end - - puts "\n\nGeneration (RouteSet): (#{(n * 8)} urls)" - per_url = gentime / (n * 8) - puts "#{per_url * 1000} ms/url" - puts "#{1 / per_url} url/s\n\n" - end end def test_route_with_colon_first @@ -1138,8 +454,7 @@ class LegacyRouteSetTests < Test::Unit::TestCase map.connect '*path', :controller => 'content', :action => 'show_file' end - recall_path = ActionController::Routing::PathSegment::Result.new(%w(pages boo)) - assert_equal '/pages/boo', rs.generate({}, :controller => 'content', :action => 'show_file', :path => recall_path) + assert_equal '/pages/boo', rs.generate({}, :controller => 'content', :action => 'show_file', :path => %w(pages boo)) end def test_backwards @@ -1455,162 +770,7 @@ class LegacyRouteSetTests < Test::Unit::TestCase end end -class RouteTest < Test::Unit::TestCase - def setup - @route = ROUTING::Route.new - end - - def slash_segment(is_optional = false) - ROUTING::DividerSegment.new('/', :optional => is_optional) - end - - def default_route - unless defined?(@default_route) - segments = [] - segments << ROUTING::StaticSegment.new('/', :raw => true) - segments << ROUTING::DynamicSegment.new(:controller) - segments << slash_segment(:optional) - segments << ROUTING::DynamicSegment.new(:action, :default => 'index', :optional => true) - segments << slash_segment(:optional) - segments << ROUTING::DynamicSegment.new(:id, :optional => true) - segments << slash_segment(:optional) - @default_route = ROUTING::Route.new(segments).freeze - end - @default_route - end - - def test_default_route_recognition - expected = {:controller => 'accounts', :action => 'show', :id => '10'} - assert_equal expected, default_route.recognize('/accounts/show/10') - assert_equal expected, default_route.recognize('/accounts/show/10/') - - expected[:id] = 'jamis' - assert_equal expected, default_route.recognize('/accounts/show/jamis/') - - expected.delete :id - assert_equal expected, default_route.recognize('/accounts/show') - assert_equal expected, default_route.recognize('/accounts/show/') - - expected[:action] = 'index' - assert_equal expected, default_route.recognize('/accounts/') - assert_equal expected, default_route.recognize('/accounts') - - assert_equal nil, default_route.recognize('/') - assert_equal nil, default_route.recognize('/accounts/how/goood/it/is/to/be/free') - end - - def test_default_route_should_omit_default_action - o = {:controller => 'accounts', :action => 'index'} - assert_equal '/accounts', default_route.generate(o, o, {}) - end - - def test_default_route_should_include_default_action_when_id_present - o = {:controller => 'accounts', :action => 'index', :id => '20'} - assert_equal '/accounts/index/20', default_route.generate(o, o, {}) - end - - def test_default_route_should_work_with_action_but_no_id - o = {:controller => 'accounts', :action => 'list_all'} - assert_equal '/accounts/list_all', default_route.generate(o, o, {}) - end - - def test_default_route_should_uri_escape_pluses - expected = { :controller => 'accounts', :action => 'show', :id => 'hello world' } - assert_equal expected, default_route.recognize('/accounts/show/hello world') - assert_equal expected, default_route.recognize('/accounts/show/hello%20world') - assert_equal '/accounts/show/hello%20world', default_route.generate(expected, expected, {}) - - expected[:id] = 'hello+world' - assert_equal expected, default_route.recognize('/accounts/show/hello+world') - assert_equal expected, default_route.recognize('/accounts/show/hello%2Bworld') - assert_equal '/accounts/show/hello+world', default_route.generate(expected, expected, {}) - end - - def test_matches_controller_and_action - # requirement_for should only be called for the action and controller _once_ - @route.expects(:requirement_for).with(:controller).times(1).returns('pages') - @route.expects(:requirement_for).with(:action).times(1).returns('show') - - @route.requirements = {:controller => 'pages', :action => 'show'} - assert @route.matches_controller_and_action?('pages', 'show') - assert !@route.matches_controller_and_action?('not_pages', 'show') - assert !@route.matches_controller_and_action?('pages', 'not_show') - end - - def test_parameter_shell - page_url = ROUTING::Route.new - page_url.requirements = {:controller => 'pages', :action => 'show', :id => /\d+/} - assert_equal({:controller => 'pages', :action => 'show'}, page_url.parameter_shell) - end - - def test_defaults - route = ROUTING::RouteBuilder.new.build '/users/:id.:format', :controller => "users", :action => "show", :format => "html" - assert_equal( - { :controller => "users", :action => "show", :format => "html" }, - route.defaults) - end - - def test_builder_complains_without_controller - assert_raise(ArgumentError) do - ROUTING::RouteBuilder.new.build '/contact', :contoller => "contact", :action => "index" - end - end - - def test_significant_keys_for_default_route - keys = default_route.significant_keys.sort_by {|k| k.to_s } - assert_equal [:action, :controller, :id], keys - end - - def test_significant_keys - segments = [] - segments << ROUTING::StaticSegment.new('/', :raw => true) - segments << ROUTING::StaticSegment.new('user') - segments << ROUTING::StaticSegment.new('/', :raw => true, :optional => true) - segments << ROUTING::DynamicSegment.new(:user) - segments << ROUTING::StaticSegment.new('/', :raw => true, :optional => true) - - requirements = {:controller => 'users', :action => 'show'} - - user_url = ROUTING::Route.new(segments, requirements) - keys = user_url.significant_keys.sort_by { |k| k.to_s } - assert_equal [:action, :controller, :user], keys - end - - def test_build_empty_query_string - assert_equal '', @route.build_query_string({}) - end - - def test_build_query_string_with_nil_value - assert_equal '', @route.build_query_string({:x => nil}) - end - - def test_simple_build_query_string - assert_equal '?x=1&y=2', order_query_string(@route.build_query_string(:x => '1', :y => '2')) - end - - def test_convert_ints_build_query_string - assert_equal '?x=1&y=2', order_query_string(@route.build_query_string(:x => 1, :y => 2)) - end - - def test_escape_spaces_build_query_string - assert_equal '?x=hello+world&y=goodbye+world', order_query_string(@route.build_query_string(:x => 'hello world', :y => 'goodbye world')) - end - - def test_expand_array_build_query_string - assert_equal '?x%5B%5D=1&x%5B%5D=2', order_query_string(@route.build_query_string(:x => [1, 2])) - end - - def test_escape_spaces_build_query_string_selected_keys - assert_equal '?x=hello+world', order_query_string(@route.build_query_string({:x => 'hello world', :y => 'goodbye world'}, [:x])) - end - - private - def order_query_string(qs) - '?' + qs[1..-1].split('&').sort.join('&') - end -end - -class RouteSetTest < Test::Unit::TestCase +class RouteSetTest < ActiveSupport::TestCase def set @set ||= ROUTING::RouteSet.new end @@ -1619,6 +779,19 @@ class RouteSetTest < Test::Unit::TestCase @request ||= ActionController::TestRequest.new end + def default_route_set + @default_route_set ||= begin + set = nil + ActionController::Routing.with_controllers(['accounts']) do + set = ROUTING::RouteSet.new + set.draw do |map| + map.connect '/:controller/:action/:id/' + end + end + set + end + end + def test_generate_extras set.draw { |m| m.connect ':controller/:action/:id' } path, extras = set.generate_extras(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world") @@ -2185,16 +1358,6 @@ class RouteSetTest < Test::Unit::TestCase Object.send(:remove_const, :Api) end - def test_generate_finds_best_fit - set.draw do |map| - map.connect "/people", :controller => "people", :action => "index" - map.connect "/ws/people", :controller => "people", :action => "index", :ws => true - end - - url = set.generate(:controller => "people", :action => "index", :ws => true) - assert_equal "/ws/people", url - end - def test_generate_changes_controller_module set.draw { |map| map.connect ':controller/:action/:id' } current = { :controller => "bling/bloop", :action => "bap", :id => 9 } @@ -2502,6 +1665,211 @@ class RouteSetTest < Test::Unit::TestCase assert_equal({:controller => 'pages', :action => 'show', :name => :as_symbol}, set.recognize_path('/named')) end + + def test_interpolation_chunk_should_respect_raw + ActionController::Routing.with_controllers(['hello']) do + set.draw do |map| + map.connect '/Hello World', :controller => 'hello' + end + + assert_equal '/Hello%20World', set.generate(:controller => 'hello') + assert_equal({:controller => "hello", :action => "index"}, set.recognize_path('/Hello World')) + assert_raise(ActionController::RoutingError) { set.recognize_path('/Hello%20World') } + end + end + + def test_value_should_not_be_double_unescaped + ActionController::Routing.with_controllers(['foo']) do + set.draw do |map| + map.connect '/Карта', :controller => 'foo' + end + + assert_equal '/%D0%9A%D0%B0%D1%80%D1%82%D0%B0', set.generate(:controller => 'foo') + assert_equal({:controller => "foo", :action => "index"}, set.recognize_path('/Карта')) + assert_raise(ActionController::RoutingError) { set.recognize_path('/%D0%9A%D0%B0%D1%80%D1%82%D0%B0') } + end + end + + def test_regexp_chunk_should_escape_specials + ActionController::Routing.with_controllers(['foo', 'bar']) do + set.draw do |map| + map.connect '/Hello*World', :controller => 'foo' + map.connect '/HelloWorld', :controller => 'bar' + end + + assert_equal '/Hello*World', set.generate(:controller => 'foo') + assert_equal '/HelloWorld', set.generate(:controller => 'bar') + + assert_equal({:controller => "foo", :action => "index"}, set.recognize_path('/Hello*World')) + assert_equal({:controller => "bar", :action => "index"}, set.recognize_path('/HelloWorld')) + end + end + + def test_regexp_chunk_should_add_question_mark_for_optionals + ActionController::Routing.with_controllers(['foo', 'bar']) do + set.draw do |map| + map.connect '/', :controller => 'foo' + map.connect '/hello', :controller => 'bar' + end + + assert_equal '/', set.generate(:controller => 'foo') + assert_equal '/hello', set.generate(:controller => 'bar') + + assert_equal({:controller => "foo", :action => "index"}, set.recognize_path('/')) + assert_equal({:controller => "bar", :action => "index"}, set.recognize_path('/hello')) + end + end + + def test_assign_route_options_with_anchor_chars + ActionController::Routing.with_controllers(['cars']) do + set.draw do |map| + map.connect '/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({:controller => "cars", :action => "buy", :person => "1", :car => "2"}, set.recognize_path('/cars/buy/1/2')) + end + end + + def test_segmentation_of_dot_path + ActionController::Routing.with_controllers(['books']) do + set.draw do |map| + map.connect '/books/:action.rss', :controller => 'books' + end + + assert_equal '/books/list.rss', set.generate(:controller => 'books', :action => 'list') + + assert_equal({:controller => "books", :action => "list"}, set.recognize_path('/books/list.rss')) + end + end + + def test_segmentation_of_dynamic_dot_path + ActionController::Routing.with_controllers(['books']) do + set.draw do |map| + map.connect '/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({: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 => "index"}, set.recognize_path('/books')) + end + 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) } + + 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({: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 + end + + def test_default_route_recognition + expected = {:controller => 'accounts', :action => 'show', :id => '10'} + assert_equal expected, default_route_set.recognize_path('/accounts/show/10') + assert_equal expected, default_route_set.recognize_path('/accounts/show/10/') + + expected[:id] = 'jamis' + assert_equal expected, default_route_set.recognize_path('/accounts/show/jamis/') + + expected.delete :id + assert_equal expected, default_route_set.recognize_path('/accounts/show') + assert_equal expected, default_route_set.recognize_path('/accounts/show/') + + expected[:action] = 'index' + assert_equal expected, default_route_set.recognize_path('/accounts/') + assert_equal expected, default_route_set.recognize_path('/accounts') + + assert_raise(ActionController::RoutingError) { default_route_set.recognize_path('/') } + assert_raise(ActionController::RoutingError) { default_route_set.recognize_path('/accounts/how/goood/it/is/to/be/free') } + end + + def test_default_route_should_omit_default_action + assert_equal '/accounts', default_route_set.generate({: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'}) + 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'}) + end + + def test_default_route_should_uri_escape_pluses + expected = { :controller => 'accounts', :action => 'show', :id => 'hello world' } + assert_equal expected, default_route_set.recognize_path('/accounts/show/hello world') + assert_equal expected, default_route_set.recognize_path('/accounts/show/hello%20world') + assert_equal '/accounts/show/hello%20world', default_route_set.generate(expected, expected) + + expected[:id] = 'hello+world' + assert_equal expected, default_route_set.recognize_path('/accounts/show/hello+world') + assert_equal expected, default_route_set.recognize_path('/accounts/show/hello%2Bworld') + assert_equal '/accounts/show/hello+world', default_route_set.generate(expected, expected) + end + + def test_parameter_shell + page_url = ROUTING::Route.new + page_url.requirements = {:controller => 'pages', :action => 'show', :id => /\d+/} + assert_equal({:controller => 'pages', :action => 'show'}, page_url.parameter_shell) + end + + def test_defaults + route = ROUTING::RouteBuilder.new.build '/users/:id.:format', :controller => "users", :action => "show", :format => "html" + assert_equal( + { :controller => "users", :action => "show", :format => "html" }, + route.defaults) + end + + def test_builder_complains_without_controller + assert_raise(ArgumentError) do + ROUTING::RouteBuilder.new.build '/contact', :contoller => "contact", :action => "index" + end + end + + def test_build_empty_query_string + assert_equal '/foo', default_route_set.generate({:controller => 'foo'}) + end + + def test_build_query_string_with_nil_value + assert_equal '/foo', default_route_set.generate({:controller => 'foo', :x => nil}) + end + + def test_simple_build_query_string + assert_equal '/foo?x=1&y=2', default_route_set.generate({:controller => 'foo', :x => '1', :y => '2'}) + end + + def test_convert_ints_build_query_string + assert_equal '/foo?x=1&y=2', default_route_set.generate({:controller => 'foo', :x => 1, :y => 2}) + end + + def test_escape_spaces_build_query_string + assert_equal '/foo?x=hello+world&y=goodbye+world', default_route_set.generate({:controller => 'foo', :x => 'hello world', :y => 'goodbye world'}) + end + + def test_expand_array_build_query_string + assert_equal '/foo?x%5B%5D=1&x%5B%5D=2', default_route_set.generate({:controller => 'foo', :x => [1, 2]}) + end + + def test_escape_spaces_build_query_string_selected_keys + assert_equal '/foo?x=hello+world', default_route_set.generate({:controller => 'foo', :x => 'hello world'}) + end end class RouteLoadingTest < Test::Unit::TestCase @@ -2565,10 +1933,10 @@ class RouteLoadingTest < Test::Unit::TestCase routes.reload end - + def test_load_multiple_configurations routes.add_configuration_file("engines.rb") - + File.expects(:stat).at_least_once.returns(@stat) routes.expects(:load).with('./config/routes.rb') diff --git a/actionpack/test/controller/test_test.rb b/actionpack/test/controller/test_test.rb index 9e88188b9a..73870a56bb 100644 --- a/actionpack/test/controller/test_test.rb +++ b/actionpack/test/controller/test_test.rb @@ -123,13 +123,6 @@ XML @controller = TestController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new - ActionController::Routing.use_controllers! %w(content admin/user test_test/test) - ActionController::Routing::Routes.load_routes! - end - - def teardown - super - ActionController::Routing::Routes.reload end def test_raw_post_handling diff --git a/actionpack/test/controller/url_rewriter_test.rb b/actionpack/test/controller/url_rewriter_test.rb index 863f8414c5..9b8d07222b 100644 --- a/actionpack/test/controller/url_rewriter_test.rb +++ b/actionpack/test/controller/url_rewriter_test.rb @@ -46,6 +46,20 @@ class UrlRewriterTests < ActionController::TestCase ) end + def test_anchor_should_call_to_param + assert_equal( + 'http://test.host/c/a/i#anchor', + @rewriter.rewrite(:controller => 'c', :action => 'a', :id => 'i', :anchor => Struct.new(:to_param).new('anchor')) + ) + end + + def test_anchor_should_be_cgi_escaped + assert_equal( + 'http://test.host/c/a/i#anc%2Fhor', + @rewriter.rewrite(:controller => 'c', :action => 'a', :id => 'i', :anchor => Struct.new(:to_param).new('anc/hor')) + ) + end + def test_overwrite_params @params[:controller] = 'hi' @params[:action] = 'bye' @@ -110,6 +124,18 @@ class UrlWriterTests < ActionController::TestCase ) end + def test_anchor_should_call_to_param + assert_equal('/c/a#anchor', + W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :anchor => Struct.new(:to_param).new('anchor')) + ) + end + + def test_anchor_should_be_cgi_escaped + assert_equal('/c/a#anc%2Fhor', + W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :anchor => Struct.new(:to_param).new('anc/hor')) + ) + end + def test_default_host add_host! assert_equal('http://www.basecamphq.com/c/a/i', @@ -195,61 +221,62 @@ class UrlWriterTests < ActionController::TestCase end def test_named_routes - ActionController::Routing::Routes.draw do |map| - map.no_args '/this/is/verbose', :controller => 'home', :action => 'index' - map.home '/home/sweet/home/:user', :controller => 'home', :action => 'index' - map.connect ':controller/:action/:id' + with_routing do |set| + set.draw do |map| + map.no_args '/this/is/verbose', :controller => 'home', :action => 'index' + map.home '/home/sweet/home/:user', :controller => 'home', :action => 'index' + map.connect ':controller/:action/:id' + end + + # We need to create a new class in order to install the new named route. + kls = Class.new { include ActionController::UrlWriter } + controller = kls.new + assert controller.respond_to?(:home_url) + assert_equal 'http://www.basecamphq.com/home/sweet/home/again', + controller.send(:home_url, :host => 'www.basecamphq.com', :user => 'again') + + assert_equal("/home/sweet/home/alabama", controller.send(:home_path, :user => 'alabama', :host => 'unused')) + assert_equal("http://www.basecamphq.com/home/sweet/home/alabama", controller.send(:home_url, :user => 'alabama', :host => 'www.basecamphq.com')) + assert_equal("http://www.basecamphq.com/this/is/verbose", controller.send(:no_args_url, :host=>'www.basecamphq.com')) end - - # We need to create a new class in order to install the new named route. - kls = Class.new { include ActionController::UrlWriter } - controller = kls.new - assert controller.respond_to?(:home_url) - assert_equal 'http://www.basecamphq.com/home/sweet/home/again', - controller.send(:home_url, :host => 'www.basecamphq.com', :user => 'again') - - assert_equal("/home/sweet/home/alabama", controller.send(:home_path, :user => 'alabama', :host => 'unused')) - assert_equal("http://www.basecamphq.com/home/sweet/home/alabama", controller.send(:home_url, :user => 'alabama', :host => 'www.basecamphq.com')) - assert_equal("http://www.basecamphq.com/this/is/verbose", controller.send(:no_args_url, :host=>'www.basecamphq.com')) - ensure - ActionController::Routing::Routes.load! end def test_relative_url_root_is_respected_for_named_routes orig_relative_url_root = ActionController::Base.relative_url_root ActionController::Base.relative_url_root = '/subdir' - ActionController::Routing::Routes.draw do |map| - map.home '/home/sweet/home/:user', :controller => 'home', :action => 'index' - end + with_routing do |set| + set.draw do |map| + map.home '/home/sweet/home/:user', :controller => 'home', :action => 'index' + end - kls = Class.new { include ActionController::UrlWriter } - controller = kls.new + kls = Class.new { include ActionController::UrlWriter } + controller = kls.new - assert_equal 'http://www.basecamphq.com/subdir/home/sweet/home/again', - controller.send(:home_url, :host => 'www.basecamphq.com', :user => 'again') + assert_equal 'http://www.basecamphq.com/subdir/home/sweet/home/again', + controller.send(:home_url, :host => 'www.basecamphq.com', :user => 'again') + end ensure - ActionController::Routing::Routes.load! ActionController::Base.relative_url_root = orig_relative_url_root end def test_only_path - ActionController::Routing::Routes.draw do |map| - map.home '/home/sweet/home/:user', :controller => 'home', :action => 'index' - map.connect ':controller/:action/:id' + with_routing do |set| + set.draw do |map| + map.home '/home/sweet/home/:user', :controller => 'home', :action => 'index' + map.connect ':controller/:action/:id' + end + + # We need to create a new class in order to install the new named route. + kls = Class.new { include ActionController::UrlWriter } + controller = kls.new + assert controller.respond_to?(:home_url) + assert_equal '/brave/new/world', + controller.send(:url_for, :controller => 'brave', :action => 'new', :id => 'world', :only_path => true) + + assert_equal("/home/sweet/home/alabama", controller.send(:home_url, :user => 'alabama', :host => 'unused', :only_path => true)) + assert_equal("/home/sweet/home/alabama", controller.send(:home_path, 'alabama')) end - - # We need to create a new class in order to install the new named route. - kls = Class.new { include ActionController::UrlWriter } - controller = kls.new - assert controller.respond_to?(:home_url) - assert_equal '/brave/new/world', - controller.send(:url_for, :controller => 'brave', :action => 'new', :id => 'world', :only_path => true) - - assert_equal("/home/sweet/home/alabama", controller.send(:home_url, :user => 'alabama', :host => 'unused', :only_path => true)) - assert_equal("/home/sweet/home/alabama", controller.send(:home_path, 'alabama')) - ensure - ActionController::Routing::Routes.load! end def test_one_parameter @@ -302,41 +329,41 @@ class UrlWriterTests < ActionController::TestCase end def test_named_routes_with_nil_keys - ActionController::Routing::Routes.clear! - ActionController::Routing::Routes.draw do |map| - map.main '', :controller => 'posts' - map.resources :posts - map.connect ':controller/:action/:id' + with_routing do |set| + set.draw do |map| + map.main '', :controller => 'posts', :format => nil + map.resources :posts + map.connect ':controller/:action/:id' + end + + # We need to create a new class in order to install the new named route. + kls = Class.new { include ActionController::UrlWriter } + kls.default_url_options[:host] = 'www.basecamphq.com' + + controller = kls.new + params = {:action => :index, :controller => :posts, :format => :xml} + assert_equal("http://www.basecamphq.com/posts.xml", controller.send(:url_for, params)) + params[:format] = nil + assert_equal("http://www.basecamphq.com/", controller.send(:url_for, params)) end - # We need to create a new class in order to install the new named route. - kls = Class.new { include ActionController::UrlWriter } - kls.default_url_options[:host] = 'www.basecamphq.com' - - controller = kls.new - params = {:action => :index, :controller => :posts, :format => :xml} - assert_equal("http://www.basecamphq.com/posts.xml", controller.send(:url_for, params)) - params[:format] = nil - assert_equal("http://www.basecamphq.com/", controller.send(:url_for, params)) - ensure - ActionController::Routing::Routes.load! end def test_formatted_url_methods_are_deprecated - ActionController::Routing::Routes.draw do |map| - map.resources :posts + with_routing do |set| + set.draw do |map| + map.resources :posts + end + # We need to create a new class in order to install the new named route. + kls = Class.new { include ActionController::UrlWriter } + controller = kls.new + params = {:id => 1, :format => :xml} + assert_deprecated do + assert_equal("/posts/1.xml", controller.send(:formatted_post_path, params)) + end + assert_deprecated do + assert_equal("/posts/1.xml", controller.send(:formatted_post_path, 1, :xml)) + end end - # We need to create a new class in order to install the new named route. - kls = Class.new { include ActionController::UrlWriter } - controller = kls.new - params = {:id => 1, :format => :xml} - assert_deprecated do - assert_equal("/posts/1.xml", controller.send(:formatted_post_path, params)) - end - assert_deprecated do - assert_equal("/posts/1.xml", controller.send(:formatted_post_path, 1, :xml)) - end - ensure - ActionController::Routing::Routes.load! end def test_multiple_includes_maintain_distinct_options diff --git a/actionpack/test/controller/verification_test.rb b/actionpack/test/controller/verification_test.rb index d568030e41..ee558f3465 100644 --- a/actionpack/test/controller/verification_test.rb +++ b/actionpack/test/controller/verification_test.rb @@ -112,7 +112,10 @@ class VerificationTest < ActionController::TestCase tests TestController setup do - ActionController::Routing::Routes.add_named_route :foo, '/foo', :controller => 'test', :action => 'foo' + ActionController::Routing::Routes.draw do |map| + map.foo '/foo', :controller => 'test', :action => 'foo' + map.connect ":controller/:action/:id" + end end def test_using_symbol_back_with_no_referrer diff --git a/actionpack/test/controller/webservice_test.rb b/actionpack/test/controller/webservice_test.rb index 9bf8da7276..916124e221 100644 --- a/actionpack/test/controller/webservice_test.rb +++ b/actionpack/test/controller/webservice_test.rb @@ -24,11 +24,6 @@ class WebServiceTest < ActionController::IntegrationTest def setup @controller = TestController.new - @default_param_parsers = ActionController::Base.param_parsers.dup - end - - def teardown - ActionController::Base.param_parsers = @default_param_parsers end def test_check_parameters @@ -110,58 +105,61 @@ class WebServiceTest < ActionController::IntegrationTest def test_post_xml_using_an_attributted_node_named_type with_test_route_set do - ActionController::Base.param_parsers[Mime::XML] = Proc.new { |data| Hash.from_xml(data)['request'].with_indifferent_access } - post "/", '<request><type type="string">Arial,12</type><z>3</z></request>', - {'CONTENT_TYPE' => 'application/xml'} - - assert_equal 'type, z', @controller.response.body - assert @controller.params.has_key?(:type) - assert_equal 'Arial,12', @controller.params['type'], @controller.params.inspect - assert_equal '3', @controller.params['z'], @controller.params.inspect + with_params_parsers Mime::XML => Proc.new { |data| Hash.from_xml(data)['request'].with_indifferent_access } do + post "/", '<request><type type="string">Arial,12</type><z>3</z></request>', + {'CONTENT_TYPE' => 'application/xml'} + + assert_equal 'type, z', @controller.response.body + assert @controller.params.has_key?(:type) + assert_equal 'Arial,12', @controller.params['type'], @controller.params.inspect + assert_equal '3', @controller.params['z'], @controller.params.inspect + end end end def test_register_and_use_yaml with_test_route_set do - ActionController::Base.param_parsers[Mime::YAML] = Proc.new { |d| YAML.load(d) } - post "/", {"entry" => "loaded from yaml"}.to_yaml, - {'CONTENT_TYPE' => 'application/x-yaml'} + with_params_parsers Mime::YAML => Proc.new { |d| YAML.load(d) } do + post "/", {"entry" => "loaded from yaml"}.to_yaml, + {'CONTENT_TYPE' => 'application/x-yaml'} - assert_equal 'entry', @controller.response.body - assert @controller.params.has_key?(:entry) - assert_equal 'loaded from yaml', @controller.params["entry"] + assert_equal 'entry', @controller.response.body + assert @controller.params.has_key?(:entry) + assert_equal 'loaded from yaml', @controller.params["entry"] + end end end def test_register_and_use_yaml_as_symbol with_test_route_set do - ActionController::Base.param_parsers[Mime::YAML] = :yaml - post "/", {"entry" => "loaded from yaml"}.to_yaml, - {'CONTENT_TYPE' => 'application/x-yaml'} + with_params_parsers Mime::YAML => :yaml do + post "/", {"entry" => "loaded from yaml"}.to_yaml, + {'CONTENT_TYPE' => 'application/x-yaml'} - assert_equal 'entry', @controller.response.body - assert @controller.params.has_key?(:entry) - assert_equal 'loaded from yaml', @controller.params["entry"] + assert_equal 'entry', @controller.response.body + assert @controller.params.has_key?(:entry) + assert_equal 'loaded from yaml', @controller.params["entry"] + end end end def test_register_and_use_xml_simple with_test_route_set do - ActionController::Base.param_parsers[Mime::XML] = Proc.new { |data| Hash.from_xml(data)['request'].with_indifferent_access } - post "/", '<request><summary>content...</summary><title>SimpleXml</title></request>', - {'CONTENT_TYPE' => 'application/xml'} - - assert_equal 'summary, title', @controller.response.body - assert @controller.params.has_key?(:summary) - assert @controller.params.has_key?(:title) - assert_equal 'content...', @controller.params["summary"] - assert_equal 'SimpleXml', @controller.params["title"] + with_params_parsers Mime::XML => Proc.new { |data| Hash.from_xml(data)['request'].with_indifferent_access } do + post "/", '<request><summary>content...</summary><title>SimpleXml</title></request>', + {'CONTENT_TYPE' => 'application/xml'} + + assert_equal 'summary, title', @controller.response.body + assert @controller.params.has_key?(:summary) + assert @controller.params.has_key?(:title) + assert_equal 'content...', @controller.params["summary"] + assert_equal 'SimpleXml', @controller.params["title"] + end end end def test_use_xml_ximple_with_empty_request with_test_route_set do - ActionController::Base.param_parsers[Mime::XML] = :xml_simple assert_nothing_raised { post "/", "", {'CONTENT_TYPE' => 'application/xml'} } assert @controller.response.body.blank? end @@ -169,7 +167,6 @@ class WebServiceTest < ActionController::IntegrationTest def test_dasherized_keys_as_xml with_test_route_set do - ActionController::Base.param_parsers[Mime::XML] = :xml_simple post "/?full=1", "<first-key>\n<sub-key>...</sub-key>\n</first-key>", {'CONTENT_TYPE' => 'application/xml'} assert_equal 'action, controller, first_key(sub_key), full', @controller.response.body @@ -179,7 +176,6 @@ class WebServiceTest < ActionController::IntegrationTest def test_typecast_as_xml with_test_route_set do - ActionController::Base.param_parsers[Mime::XML] = :xml_simple xml = <<-XML <data> <a type="integer">15</a> @@ -208,7 +204,6 @@ class WebServiceTest < ActionController::IntegrationTest def test_entities_unescaped_as_xml_simple with_test_route_set do - ActionController::Base.param_parsers[Mime::XML] = :xml_simple xml = <<-XML <data><foo "bar's" & friends></data> XML @@ -219,34 +214,44 @@ class WebServiceTest < ActionController::IntegrationTest def test_typecast_as_yaml with_test_route_set do - ActionController::Base.param_parsers[Mime::YAML] = :yaml - yaml = <<-YAML - --- - data: - a: 15 - b: false - c: true - d: 2005-03-17 - e: 2005-03-17T21:41:07Z - f: unparsed - g: - - 1 - - hello - - 1974-07-25 - YAML - post "/", yaml, {'CONTENT_TYPE' => 'application/x-yaml'} - params = @controller.params - assert_equal 15, params[:data][:a] - assert_equal false, params[:data][:b] - assert_equal true, params[:data][:c] - assert_equal Date.new(2005,3,17), params[:data][:d] - assert_equal Time.utc(2005,3,17,21,41,7), params[:data][:e] - assert_equal "unparsed", params[:data][:f] - assert_equal [1, "hello", Date.new(1974,7,25)], params[:data][:g] + with_params_parsers Mime::YAML => :yaml do + yaml = <<-YAML + --- + data: + a: 15 + b: false + c: true + d: 2005-03-17 + e: 2005-03-17T21:41:07Z + f: unparsed + g: + - 1 + - hello + - 1974-07-25 + YAML + post "/", yaml, {'CONTENT_TYPE' => 'application/x-yaml'} + params = @controller.params + assert_equal 15, params[:data][:a] + assert_equal false, params[:data][:b] + assert_equal true, params[:data][:c] + assert_equal Date.new(2005,3,17), params[:data][:d] + assert_equal Time.utc(2005,3,17,21,41,7), params[:data][:e] + assert_equal "unparsed", params[:data][:f] + assert_equal [1, "hello", Date.new(1974,7,25)], params[:data][:g] + end end end private + def with_params_parsers(parsers = {}) + old_session = @integration_session + app = ActionDispatch::ParamsParser.new(ActionController::Routing::Routes, parsers) + @integration_session = open_session(app) + yield + ensure + @integration_session = old_session + end + def with_test_route_set with_routing do |set| set.draw do |map| @@ -254,6 +259,7 @@ class WebServiceTest < ActionController::IntegrationTest c.connect "/", :action => "assign_parameters" end end + reset! yield end end diff --git a/actionpack/test/dispatch/mime_type_test.rb b/actionpack/test/dispatch/mime_type_test.rb index 4ea0fedb8f..0832943d4c 100644 --- a/actionpack/test/dispatch/mime_type_test.rb +++ b/actionpack/test/dispatch/mime_type_test.rb @@ -56,7 +56,7 @@ class MimeTypeTest < ActiveSupport::TestCase test "type convenience methods" do # Don't test Mime::ALL, since it Mime::ALL#html? == true - types = Mime::SET.symbols.uniq - [:all] + types = Mime::SET.symbols.uniq - [:all, :iphone] # Remove custom Mime::Type instances set in other tests, like Mime::GIF and Mime::IPHONE types.delete_if { |type| !Mime.const_defined?(type.to_s.upcase) } diff --git a/actionpack/test/dispatch/request/json_params_parsing_test.rb b/actionpack/test/dispatch/request/json_params_parsing_test.rb index a3dde72c4e..995f36bb29 100644 --- a/actionpack/test/dispatch/request/json_params_parsing_test.rb +++ b/actionpack/test/dispatch/request/json_params_parsing_test.rb @@ -30,16 +30,37 @@ class JsonParamsParsingTest < ActionController::IntegrationTest ) end + test "logs error if parsing unsuccessful" do + with_test_routing do + begin + $stderr = StringIO.new + json = "[\"person]\": {\"name\": \"David\"}}" + post "/parse", json, {'CONTENT_TYPE' => 'application/json'} + assert_response :error + $stderr.rewind && err = $stderr.read + assert err =~ /Error occurred while parsing request parameters/ + ensure + $stderr = STDERR + end + end + end + private def assert_parses(expected, actual, headers = {}) + with_test_routing do + post "/parse", actual, headers + assert_response :ok + assert_equal(expected, TestController.last_request_parameters) + end + end + + def with_test_routing with_routing do |set| set.draw do |map| map.connect ':action', :controller => "json_params_parsing_test/test" end - - post "/parse", actual, headers - assert_response :ok - assert_equal(expected, TestController.last_request_parameters) + reset! + yield end end end diff --git a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb index 301080842e..d4ee4362eb 100644 --- a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb +++ b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb @@ -153,6 +153,7 @@ class MultipartParamsParsingTest < ActionController::IntegrationTest set.draw do |map| map.connect ':action', :controller => "multipart_params_parsing_test/test" end + reset! yield end end diff --git a/actionpack/test/dispatch/request/query_string_parsing_test.rb b/actionpack/test/dispatch/request/query_string_parsing_test.rb index a31e326ddf..2261934e45 100644 --- a/actionpack/test/dispatch/request/query_string_parsing_test.rb +++ b/actionpack/test/dispatch/request/query_string_parsing_test.rb @@ -111,6 +111,7 @@ class QueryStringParsingTest < ActionController::IntegrationTest set.draw do |map| map.connect ':action', :controller => "query_string_parsing_test/test" end + reset! get "/parse", actual assert_response :ok diff --git a/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb b/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb index 7167cdafac..6c9967d26e 100644 --- a/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb +++ b/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb @@ -132,6 +132,7 @@ class UrlEncodedParamsParsingTest < ActionController::IntegrationTest set.draw do |map| map.connect ':action', :controller => "url_encoded_params_parsing_test/test" end + reset! yield end end diff --git a/actionpack/test/dispatch/request/xml_params_parsing_test.rb b/actionpack/test/dispatch/request/xml_params_parsing_test.rb index ee764e726e..2f2dd695c4 100644 --- a/actionpack/test/dispatch/request/xml_params_parsing_test.rb +++ b/actionpack/test/dispatch/request/xml_params_parsing_test.rb @@ -38,6 +38,21 @@ class XmlParamsParsingTest < ActionController::IntegrationTest end end + test "logs error if parsing unsuccessful" do + with_test_routing do + begin + $stderr = StringIO.new + xml = "<person><name>David</name><avatar type='file' name='me.jpg' content_type='image/jpg'>#{ActiveSupport::Base64.encode64('ABC')}</avatar></pineapple>" + post "/parse", xml, default_headers + assert_response :error + $stderr.rewind && err = $stderr.read + assert err =~ /Error occurred while parsing request parameters/ + ensure + $stderr = STDERR + end + end + end + test "parses multiple files" do xml = <<-end_body <person> @@ -71,6 +86,7 @@ class XmlParamsParsingTest < ActionController::IntegrationTest set.draw do |map| map.connect ':action', :controller => "xml_params_parsing_test/test" end + reset! yield end end @@ -85,4 +101,4 @@ class LegacyXmlParamsParsingTest < XmlParamsParsingTest def default_headers {'HTTP_X_POST_DATA_FORMAT' => 'xml'} end -end +end
\ No newline at end of file diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb index f3500fca34..239fda98e0 100644 --- a/actionpack/test/dispatch/request_test.rb +++ b/actionpack/test/dispatch/request_test.rb @@ -366,12 +366,12 @@ class RequestTest < ActiveSupport::TestCase end test "XMLHttpRequest" do - with_accept_header false do - request = stub_request 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest' - request.expects(:parameters).at_least_once.returns({}) - assert request.xhr? - assert_equal Mime::JS, request.format - end + request = stub_request 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest', + 'HTTP_ACCEPT' => + [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(",") + request.expects(:parameters).at_least_once.returns({}) + assert request.xhr? + assert_equal Mime::JS, request.format end test "content type" do @@ -420,37 +420,34 @@ class RequestTest < ActiveSupport::TestCase end test "formats with accept header" do - with_accept_header true do - request = stub_request 'HTTP_ACCEPT' => 'text/html' - request.expects(:parameters).at_least_once.returns({}) - assert_equal [ Mime::HTML ], request.formats - - request = stub_request 'CONTENT_TYPE' => 'application/xml; charset=UTF-8' - request.expects(:parameters).at_least_once.returns({}) - assert_equal with_set(Mime::XML, Mime::HTML), request.formats - end + request = stub_request 'HTTP_ACCEPT' => 'text/html' + request.expects(:parameters).at_least_once.returns({}) + assert_equal [ Mime::HTML ], request.formats - with_accept_header false do - request = stub_request - request.expects(:parameters).at_least_once.returns({ :format => :txt }) - assert_equal with_set(Mime::TEXT), request.formats - end + request = stub_request 'CONTENT_TYPE' => 'application/xml; charset=UTF-8', + 'HTTP_X_REQUESTED_WITH' => "XMLHttpRequest" + request.expects(:parameters).at_least_once.returns({}) + assert_equal with_set(Mime::XML), request.formats + + request = stub_request + request.expects(:parameters).at_least_once.returns({ :format => :txt }) + assert_equal with_set(Mime::TEXT), request.formats end test "negotiate_mime" do - with_accept_header true do - request = stub_request 'HTTP_ACCEPT' => 'text/html' - request.expects(:parameters).at_least_once.returns({}) - - assert_equal nil, request.negotiate_mime([Mime::XML, Mime::JSON]) - assert_equal Mime::HTML, request.negotiate_mime([Mime::XML, Mime::HTML]) - assert_equal Mime::HTML, request.negotiate_mime([Mime::XML, Mime::ALL]) - - request = stub_request 'CONTENT_TYPE' => 'application/xml; charset=UTF-8' - request.expects(:parameters).at_least_once.returns({}) - assert_equal Mime::XML, request.negotiate_mime([Mime::XML, Mime::CSV]) - assert_equal Mime::CSV, request.negotiate_mime([Mime::CSV, Mime::YAML]) - end + request = stub_request 'HTTP_ACCEPT' => 'text/html', + 'HTTP_X_REQUESTED_WITH' => "XMLHttpRequest" + + request.expects(:parameters).at_least_once.returns({}) + + assert_equal nil, request.negotiate_mime([Mime::XML, Mime::JSON]) + assert_equal Mime::HTML, request.negotiate_mime([Mime::XML, Mime::HTML]) + assert_equal Mime::HTML, request.negotiate_mime([Mime::XML, Mime::ALL]) + + request = stub_request 'CONTENT_TYPE' => 'application/xml; charset=UTF-8', + 'HTTP_X_REQUESTED_WITH' => "XMLHttpRequest" + request.expects(:parameters).at_least_once.returns({}) + assert_equal Mime::XML, request.negotiate_mime([Mime::XML, Mime::CSV]) end protected @@ -460,7 +457,7 @@ protected end def with_set(*args) - args + Mime::SET + args end def with_accept_header(value) diff --git a/actionpack/test/dispatch/session/cookie_store_test.rb b/actionpack/test/dispatch/session/cookie_store_test.rb index 2db76818ac..0723a76d2b 100644 --- a/actionpack/test/dispatch/session/cookie_store_test.rb +++ b/actionpack/test/dispatch/session/cookie_store_test.rb @@ -8,10 +8,6 @@ class CookieStoreTest < ActionController::IntegrationTest # Make sure Session middleware doesnt get included in the middleware stack ActionController::Base.session_store = nil - DispatcherApp = ActionController::Dispatcher.new - CookieStoreApp = ActionDispatch::Session::CookieStore.new(DispatcherApp, - :key => SessionKey, :secret => SessionSecret) - Verifier = ActiveSupport::MessageVerifier.new(SessionSecret, 'SHA1') SignedBar = Verifier.generate(:foo => "bar", :session_id => ActiveSupport::SecureRandom.hex(16)) @@ -51,7 +47,7 @@ class CookieStoreTest < ActionController::IntegrationTest end def setup - @integration_session = open_session(CookieStoreApp) + reset_app! end def test_raises_argument_error_if_missing_session_key @@ -197,10 +193,10 @@ class CookieStoreTest < ActionController::IntegrationTest end def test_session_store_with_expire_after - app = ActionDispatch::Session::CookieStore.new(DispatcherApp, :key => SessionKey, :secret => SessionSecret, :expire_after => 5.hours) - @integration_session = open_session(app) - with_test_route_set do + app = ActionDispatch::Session::CookieStore.new(ActionController::Dispatcher.new, :key => SessionKey, :secret => SessionSecret, :expire_after => 5.hours) + @integration_session = open_session(app) + # First request accesses the session time = Time.local(2008, 4, 24) Time.stubs(:now).returns(time) @@ -230,6 +226,12 @@ class CookieStoreTest < ActionController::IntegrationTest end private + def reset_app! + app = ActionDispatch::Session::CookieStore.new(ActionController::Dispatcher.new, + :key => SessionKey, :secret => SessionSecret) + @integration_session = open_session(app) + end + def with_test_route_set with_routing do |set| set.draw do |map| @@ -237,6 +239,7 @@ class CookieStoreTest < ActionController::IntegrationTest c.connect "/:action" end end + reset_app! yield end end diff --git a/actionpack/test/dispatch/session/mem_cache_store_test.rb b/actionpack/test/dispatch/session/mem_cache_store_test.rb index 7561c93e4a..1588918be7 100644 --- a/actionpack/test/dispatch/session/mem_cache_store_test.rb +++ b/actionpack/test/dispatch/session/mem_cache_store_test.rb @@ -32,14 +32,7 @@ class MemCacheStoreTest < ActionController::IntegrationTest end begin - DispatcherApp = ActionController::Dispatcher.new - MemCacheStoreApp = ActionDispatch::Session::MemCacheStore.new( - DispatcherApp, :key => '_session_id') - - - def setup - @integration_session = open_session(MemCacheStoreApp) - end + App = ActionDispatch::Session::MemCacheStore.new(ActionController::Dispatcher.new, :key => '_session_id') def test_setting_and_getting_session_value with_test_route_set do @@ -114,6 +107,12 @@ class MemCacheStoreTest < ActionController::IntegrationTest end private + def reset_app! + app = ActionDispatch::Session::MemCacheStore.new( + ActionController::Dispatcher.new, :key => '_session_id') + @integration_session = open_session(app) + end + def with_test_route_set with_routing do |set| set.draw do |map| @@ -121,6 +120,7 @@ class MemCacheStoreTest < ActionController::IntegrationTest c.connect "/:action" end end + reset_app! yield end end diff --git a/actionpack/test/fixtures/content_type/render_default_content_types_for_respond_to.rhtml b/actionpack/test/fixtures/content_type/render_default_content_types_for_respond_to.xml.erb index 25dc746886..25dc746886 100644 --- a/actionpack/test/fixtures/content_type/render_default_content_types_for_respond_to.rhtml +++ b/actionpack/test/fixtures/content_type/render_default_content_types_for_respond_to.xml.erb diff --git a/actionpack/test/fixtures/test/_customer_with_var.erb b/actionpack/test/fixtures/test/_customer_with_var.erb index 3379246b7e..00047dd20e 100644 --- a/actionpack/test/fixtures/test/_customer_with_var.erb +++ b/actionpack/test/fixtures/test/_customer_with_var.erb @@ -1 +1 @@ -<%= customer.name %> <%= object.name %> <%= customer_with_var.name %>
\ No newline at end of file +<%= customer.name %> <%= customer.name %> <%= customer.name %>
\ No newline at end of file diff --git a/actionpack/test/fixtures/test/_hash_object.erb b/actionpack/test/fixtures/test/_hash_object.erb index 55c03afb27..34a92c6a56 100644 --- a/actionpack/test/fixtures/test/_hash_object.erb +++ b/actionpack/test/fixtures/test/_hash_object.erb @@ -1,2 +1,2 @@ <%= hash_object[:first_name] %> -<%= object[:first_name].reverse %> +<%= hash_object[:first_name].reverse %> diff --git a/actionpack/test/fixtures/test/using_layout_around_block_with_args.html.erb b/actionpack/test/fixtures/test/using_layout_around_block_with_args.html.erb deleted file mode 100644 index 71b1f30ad0..0000000000 --- a/actionpack/test/fixtures/test/using_layout_around_block_with_args.html.erb +++ /dev/null @@ -1 +0,0 @@ -<% render(:layout => "layout_for_block_with_args") do |*args| %><%= args.join %><% end %>
\ No newline at end of file diff --git a/actionpack/test/lib/controller/fake_controllers.rb b/actionpack/test/lib/controller/fake_controllers.rb index 75c114c103..6e02e2d21b 100644 --- a/actionpack/test/lib/controller/fake_controllers.rb +++ b/actionpack/test/lib/controller/fake_controllers.rb @@ -1,15 +1,16 @@ class << Object; alias_method :const_available?, :const_defined?; end - -class ContentController < Class.new(ActionController::Base) + +class ContentController < ActionController::Base end class NotAController end module Admin class << self; alias_method :const_available?, :const_defined?; end - class UserController < Class.new(ActionController::Base); end - class NewsFeedController < Class.new(ActionController::Base); end + class UserController < ActionController::Base; end + class NewsFeedController < ActionController::Base; end end + # For speed test class SpeedController < ActionController::Base; end class SearchController < SpeedController; end diff --git a/actionpack/test/lib/controller/fake_models.rb b/actionpack/test/lib/controller/fake_models.rb index 0faf8f3f9a..18eff7516b 100644 --- a/actionpack/test/lib/controller/fake_models.rb +++ b/actionpack/test/lib/controller/fake_models.rb @@ -10,12 +10,16 @@ class Customer < Struct.new(:name, :id) id.to_s end - def to_xml - "XML" + def to_xml(options={}) + if options[:builder] + options[:builder].name name + else + "<name>#{name}</name>" + end end - def to_js - "JS" + def to_js(options={}) + "name: #{name.inspect}" end def errors diff --git a/actionpack/test/lib/fixture_template.rb b/actionpack/test/lib/fixture_template.rb index ee526b5de5..8da92180d1 100644 --- a/actionpack/test/lib/fixture_template.rb +++ b/actionpack/test/lib/fixture_template.rb @@ -4,7 +4,7 @@ module ActionView #:nodoc: super(options) @hash = hash end - + def find_templates(name, details, prefix, partial) if regexp = details_to_regexp(name, details, prefix, partial) cached(regexp) do @@ -16,26 +16,26 @@ module ActionView #:nodoc: end end end - + private - + def formats_regexp @formats_regexp ||= begin formats = Mime::SET.symbols '(?:' + formats.map { |l| "\\.#{Regexp.escape(l.to_s)}" }.join('|') + ')?' end end - + def handler_regexp e = TemplateHandlers.extensions.map{|h| "\\.#{Regexp.escape(h.to_s)}"}.join("|") - "(?:#{e})?" + "(?:#{e})" end - + def details_to_regexp(name, details, prefix, partial) path = "" path << "#{prefix}/" unless prefix.empty? path << (partial ? "_#{name}" : name) - + extensions = "" [:locales, :formats].each do |k| extensions << if exts = details[k] @@ -47,7 +47,7 @@ module ActionView #:nodoc: %r'^#{Regexp.escape(path)}#{extensions}#{handler_regexp}$' end - + # TODO: fix me # :api: plugin def path_to_details(path) @@ -56,10 +56,10 @@ module ActionView #:nodoc: partial = m[1] == '_' details = (m[2]||"").split('.').reject { |e| e.empty? } handler = Template.handler_class_for_extension(m[3]) - + format = Mime[details.last] && details.pop.to_sym locale = details.last && details.pop.to_sym - + return handler, :format => format, :locale => locale, :partial => partial end end diff --git a/actionpack/test/new_base/content_type_test.rb b/actionpack/test/new_base/content_type_test.rb index cfc03a3024..ceee508224 100644 --- a/actionpack/test/new_base/content_type_test.rb +++ b/actionpack/test/new_base/content_type_test.rb @@ -75,7 +75,7 @@ module ContentType end test "sets Content-Type as application/xml when rendering *.xml.erb" do - get "/content_type/implied/i_am_xml_erb" + get "/content_type/implied/i_am_xml_erb", "format" => "xml" assert_header "Content-Type", "application/xml; charset=utf-8" end @@ -87,7 +87,7 @@ module ContentType end test "sets Content-Type as application/xml when rendering *.xml.builder" do - get "/content_type/implied/i_am_xml_builder" + get "/content_type/implied/i_am_xml_builder", "format" => "xml" assert_header "Content-Type", "application/xml; charset=utf-8" end diff --git a/actionpack/test/new_base/metal_test.rb b/actionpack/test/new_base/metal_test.rb new file mode 100644 index 0000000000..2b7720863a --- /dev/null +++ b/actionpack/test/new_base/metal_test.rb @@ -0,0 +1,44 @@ +require File.join(File.expand_path(File.dirname(__FILE__)), "test_helper") + +module MetalTest + class MetalMiddleware < ActionController::Middleware + def call(env) + if env["PATH_INFO"] =~ /authed/ + app.call(env) + else + [401, headers, "Not authed!"] + end + end + end + + class Endpoint + def call(env) + [200, {}, "Hello World"] + end + end + + class TestMiddleware < ActiveSupport::TestCase + def setup + @app = Rack::Builder.new do + use MetalMiddleware + run Endpoint.new + end.to_app + end + + test "it can call the next app by using @app" do + env = Rack::MockRequest.env_for("/authed") + response = @app.call(env) + + assert_equal "Hello World", response[2] + end + + test "it can return a response using the normal AC::Metal techniques" do + env = Rack::MockRequest.env_for("/") + response = @app.call(env) + + assert_equal "Not authed!", response[2] + assert_equal 401, response[0] + end + end +end + diff --git a/actionpack/test/new_base/render_layout_test.rb b/actionpack/test/new_base/render_layout_test.rb index 279b807a5f..933eef58e7 100644 --- a/actionpack/test/new_base/render_layout_test.rb +++ b/actionpack/test/new_base/render_layout_test.rb @@ -83,7 +83,7 @@ module ControllerLayouts testing ControllerLayouts::MismatchFormatController test "if JS is selected, an HTML template is not also selected" do - get :index + get :index, "format" => "js" assert_response "$(\"test\").omg();" end diff --git a/actionpack/test/new_base/render_rjs_test.rb b/actionpack/test/new_base/render_rjs_test.rb index bd4c87b3bf..3d3e516905 100644 --- a/actionpack/test/new_base/render_rjs_test.rb +++ b/actionpack/test/new_base/render_rjs_test.rb @@ -21,24 +21,23 @@ module RenderRjs def index_locale old_locale, I18n.locale = I18n.locale, :da end - end class TestBasic < SimpleRouteCase testing BasicController test "rendering a partial in an RJS template should pick the JS template over the HTML one" do - get :index + get :index, "format" => "js" assert_response("$(\"customer\").update(\"JS Partial\");") end test "replacing an element with a partial in an RJS template should pick the HTML template over the JS one" do - get :index_html + get :index_html, "format" => "js" assert_response("$(\"customer\").update(\"HTML Partial\");") end test "replacing an element with a partial in an RJS template with a locale should pick the localed HTML template" do - get :index_locale, :format => :js + get :index_locale, "format" => "js" assert_response("$(\"customer\").update(\"Danish HTML Partial\");") end diff --git a/actionpack/test/new_base/render_template_test.rb b/actionpack/test/new_base/render_template_test.rb index 94ea38fc7b..967cbd07b0 100644 --- a/actionpack/test/new_base/render_template_test.rb +++ b/actionpack/test/new_base/render_template_test.rb @@ -73,7 +73,7 @@ module RenderTemplate end test "rendering a builder template" do - get :builder_template + get :builder_template, "format" => "xml" assert_response "<html>\n <p>Hello</p>\n</html>\n" end end diff --git a/actionpack/test/new_base/test_helper.rb b/actionpack/test/new_base/test_helper.rb index 9271b2dd59..b7ccd3db8d 100644 --- a/actionpack/test/new_base/test_helper.rb +++ b/actionpack/test/new_base/test_helper.rb @@ -35,12 +35,6 @@ class Rack::TestCase < ActionController::IntegrationTest setup do ActionController::Base.session_options[:key] = "abc" ActionController::Base.session_options[:secret] = ("*" * 30) - - controllers = ActionController::Base.subclasses.map do |k| - k.underscore.sub(/_controller$/, '') - end - - ActionController::Routing.use_controllers!(controllers) end def app @@ -91,10 +85,26 @@ end class ::ApplicationController < ActionController::Base end +module ActionController + class << Routing + def possible_controllers + @@possible_controllers ||= [] + end + end + + class Base + def self.inherited(klass) + name = klass.name.underscore.sub(/_controller$/, '') + ActionController::Routing.possible_controllers << name unless name.blank? + super + end + end +end + class SimpleRouteCase < Rack::TestCase setup do ActionController::Routing::Routes.draw do |map| map.connect ':controller/:action/:id' end end -end
\ No newline at end of file +end diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb index 2b1d80b1bf..8fd018f86d 100644 --- a/actionpack/test/template/form_helper_test.rb +++ b/actionpack/test/template/form_helper_test.rb @@ -157,6 +157,22 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal('<label for="my_for">Title</label>', label(:post, :title, nil, "for" => "my_for")) end + def test_label_with_id_attribute_as_symbol + assert_dom_equal('<label for="post_title" id="my_id">Title</label>', label(:post, :title, nil, :id => "my_id")) + end + + def test_label_with_id_attribute_as_string + assert_dom_equal('<label for="post_title" id="my_id">Title</label>', label(:post, :title, nil, "id" => "my_id")) + end + + def test_label_with_for_and_id_attributes_as_symbol + assert_dom_equal('<label for="my_for" id="my_id">Title</label>', label(:post, :title, nil, :for => "my_for", :id => "my_id")) + end + + def test_label_with_for_and_id_attributes_as_string + assert_dom_equal('<label for="my_for" id="my_id">Title</label>', label(:post, :title, nil, "for" => "my_for", "id" => "my_id")) + end + def test_label_for_radio_buttons_with_value assert_dom_equal('<label for="post_title_great_title">The title goes here</label>', label("post", "title", "The title goes here", :value => "great_title")) assert_dom_equal('<label for="post_title_great_title">The title goes here</label>', label("post", "title", "The title goes here", :value => "great title")) diff --git a/actionpack/test/template/form_options_helper_i18n_test.rb b/actionpack/test/template/form_options_helper_i18n_test.rb new file mode 100644 index 0000000000..91e370efa7 --- /dev/null +++ b/actionpack/test/template/form_options_helper_i18n_test.rb @@ -0,0 +1,27 @@ +require 'abstract_unit' + +class FormOptionsHelperI18nTests < ActionView::TestCase + tests ActionView::Helpers::FormOptionsHelper + + def setup + @prompt_message = 'Select!' + I18n.backend.send(:init_translations) + I18n.backend.store_translations :en, :support => { :select => { :prompt => @prompt_message } } + end + + def teardown + I18n.backend = I18n::Backend::Simple.new + end + + def test_select_with_prompt_true_translates_prompt_message + I18n.expects(:translate).with('support.select.prompt', { :default => 'Please select' }) + select('post', 'category', [], :prompt => true) + end + + def test_select_with_translated_prompt + assert_dom_equal( + %Q(<select id="post_category" name="post[category]"><option value="">#{@prompt_message}</option>\n</select>), + select('post', 'category', [], :prompt => true) + ) + end +end
\ No newline at end of file diff --git a/actionpack/test/template/form_options_helper_test.rb b/actionpack/test/template/form_options_helper_test.rb index 73624406be..aa40e46aa8 100644 --- a/actionpack/test/template/form_options_helper_test.rb +++ b/actionpack/test/template/form_options_helper_test.rb @@ -763,6 +763,40 @@ class FormOptionsHelperTest < ActionView::TestCase html end + def test_grouped_collection_select + @continents = [ + Continent.new("<Africa>", [Country.new("<sa>", "<South Africa>"), Country.new("so", "Somalia")] ), + Continent.new("Europe", [Country.new("dk", "Denmark"), Country.new("ie", "Ireland")] ) + ] + + @post = Post.new + @post.origin = 'dk' + + assert_dom_equal( + %Q{<select id="post_origin" name="post[origin]"><optgroup label="<Africa>"><option value="<sa>"><South Africa></option>\n<option value="so">Somalia</option></optgroup><optgroup label="Europe"><option value="dk" selected="selected">Denmark</option>\n<option value="ie">Ireland</option></optgroup></select>}, + grouped_collection_select("post", "origin", @continents, :countries, :continent_name, :country_id, :country_name) + ) + end + + def test_grouped_collection_select_under_fields_for + @continents = [ + Continent.new("<Africa>", [Country.new("<sa>", "<South Africa>"), Country.new("so", "Somalia")] ), + Continent.new("Europe", [Country.new("dk", "Denmark"), Country.new("ie", "Ireland")] ) + ] + + @post = Post.new + @post.origin = 'dk' + + fields_for :post, @post do |f| + concat f.grouped_collection_select("origin", @continents, :countries, :continent_name, :country_id, :country_name) + end + + assert_dom_equal( + %Q{<select id="post_origin" name="post[origin]"><optgroup label="<Africa>"><option value="<sa>"><South Africa></option>\n<option value="so">Somalia</option></optgroup><optgroup label="Europe"><option value="dk" selected="selected">Denmark</option>\n<option value="ie">Ireland</option></optgroup></select>}, + output_buffer + ) + end + private def dummy_posts diff --git a/actionpack/test/template/javascript_helper_test.rb b/actionpack/test/template/javascript_helper_test.rb index 8caabfc3e1..f0f686f6e2 100644 --- a/actionpack/test/template/javascript_helper_test.rb +++ b/actionpack/test/template/javascript_helper_test.rb @@ -7,6 +7,10 @@ class JavaScriptHelperTest < ActionView::TestCase attr_accessor :formats, :output_buffer + def reset_formats(format) + @format = format + end + def setup super @template = self diff --git a/actionpack/test/template/prototype_helper_test.rb b/actionpack/test/template/prototype_helper_test.rb index acbf311212..313a769088 100644 --- a/actionpack/test/template/prototype_helper_test.rb +++ b/actionpack/test/template/prototype_helper_test.rb @@ -36,6 +36,10 @@ class Author::Nested < Author; end class PrototypeHelperBaseTest < ActionView::TestCase attr_accessor :formats, :output_buffer + def reset_formats(format) + @format = format + end + def setup super @template = self diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb index 7f30ae88a1..c86d5215cd 100644 --- a/actionpack/test/template/render_test.rb +++ b/actionpack/test/template/render_test.rb @@ -2,10 +2,14 @@ require 'abstract_unit' require 'controller/fake_models' +class TestController < ActionController::Base +end + module RenderTestCases def setup_view(paths) @assigns = { :secret => 'in the sauce' } @view = ActionView::Base.new(paths, @assigns) + @controller_view = ActionView::Base.for_controller(TestController.new) # Reload and register danish language for testing I18n.reload! @@ -138,7 +142,7 @@ module RenderTestCases end def test_render_partial_collection_without_as - assert_equal "local_inspector,local_inspector_counter,object", + assert_equal "local_inspector,local_inspector_counter", @view.render(:partial => "test/local_inspector", :collection => [ Customer.new("mary") ]) end @@ -158,6 +162,25 @@ module RenderTestCases assert_nil @view.render(:partial => []) end + def test_render_partial_using_string + assert_equal "Hello: Anonymous", @controller_view.render('customer') + end + + def test_render_partial_with_locals_using_string + assert_equal "Hola: david", @controller_view.render('customer_greeting', :greeting => 'Hola', :customer_greeting => Customer.new("david")) + end + + def test_render_partial_using_object + assert_equal "Hello: lifo", + @controller_view.render(Customer.new("lifo"), :greeting => "Hello") + end + + def test_render_partial_using_collection + customers = [ Customer.new("Amazon"), Customer.new("Yahoo") ] + assert_equal "Hello: AmazonHello: Yahoo", + @controller_view.render(customers, :greeting => "Hello") + end + # TODO: The reason for this test is unclear, improve documentation def test_render_partial_and_fallback_to_layout assert_equal "Before (Josh)\n\nAfter", @view.render(:partial => "test/layout_for_partial", :locals => { :name => "Josh" }) @@ -167,6 +190,8 @@ module RenderTestCases def test_render_missing_xml_partial_and_raise_missing_template @view.formats = [:xml] assert_raise(ActionView::MissingTemplate) { @view.render(:partial => "test/layout_for_partial") } + ensure + @view.formats = nil end def test_render_inline @@ -196,17 +221,6 @@ module RenderTestCases assert_equal 'source: "Hello, <%= name %>!"', @view.render(:inline => "Hello, <%= name %>!", :locals => { :name => "Josh" }, :type => :foo) end - class LegacyHandler < ActionView::TemplateHandler - def render(template, local_assigns) - "source: #{template.source}; locals: #{local_assigns.inspect}" - end - end - - def test_render_legacy_handler_with_custom_type - ActionView::Template.register_template_handler :foo, LegacyHandler - assert_equal 'source: Hello, <%= name %>!; locals: {:name=>"Josh"}', @view.render(:inline => "Hello, <%= name %>!", :locals => { :name => "Josh" }, :type => :foo) - end - def test_render_ignores_templates_with_malformed_template_handlers %w(malformed malformed.erb malformed.html.erb malformed.en.html.erb).each do |name| assert_raise(ActionView::MissingTemplate) { @view.render(:file => "test/malformed/#{name}") } diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb index b7823b9394..08143ba680 100644 --- a/actionpack/test/template/text_helper_test.rb +++ b/actionpack/test/template/text_helper_test.rb @@ -1,6 +1,10 @@ require 'abstract_unit' require 'testing_sandbox' -require 'redcloth' +begin + require 'redcloth' +rescue LoadError + $stderr.puts "Skipping textilize tests. `gem install RedCloth` to enable." +end class TextHelperTest < ActionView::TestCase tests ActionView::Helpers::TextHelper @@ -530,19 +534,21 @@ class TextHelperTest < ActionView::TestCase assert_equal(%w{Specialized Fuji Giant}, @cycles) end - def test_textilize - assert_equal("<p><strong>This is Textile!</strong> Rejoice!</p>", textilize("*This is Textile!* Rejoice!")) - end + if defined? RedCloth + def test_textilize + assert_equal("<p><strong>This is Textile!</strong> Rejoice!</p>", textilize("*This is Textile!* Rejoice!")) + end - def test_textilize_with_blank - assert_equal("", textilize("")) - end + def test_textilize_with_blank + assert_equal("", textilize("")) + end - def test_textilize_with_options - assert_equal("<p>This is worded <strong>strongly</strong></p>", textilize("This is worded <strong>strongly</strong>", :filter_html)) - end + def test_textilize_with_options + assert_equal("<p>This is worded <strong>strongly</strong></p>", textilize("This is worded <strong>strongly</strong>", :filter_html)) + end - def test_textilize_with_hard_breaks - assert_equal("<p>This is one scary world.<br />\n True.</p>", textilize("This is one scary world.\n True.")) + def test_textilize_with_hard_breaks + assert_equal("<p>This is one scary world.<br />\n True.</p>", textilize("This is one scary world.\n True.")) + end end end diff --git a/actionpack/test/template/url_helper_test.rb b/actionpack/test/template/url_helper_test.rb index 9eeb26831c..0e24fbd24d 100644 --- a/actionpack/test/template/url_helper_test.rb +++ b/actionpack/test/template/url_helper_test.rb @@ -220,6 +220,14 @@ class UrlHelperTest < ActionView::TestCase ) end + def test_link_tag_using_delete_javascript_and_href_and_confirm + assert_dom_equal( + "<a href='\#' onclick=\"if (confirm('Are you serious?')) { var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = 'http://www.example.com';var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method'); m.setAttribute('value', 'delete'); f.appendChild(m);f.submit(); };return false;\">Destroy</a>", + link_to("Destroy", "http://www.example.com", :method => :delete, :href => '#', :confirm => "Are you serious?"), + "When specifying url, form should be generated with it, but not this.href" + ) + end + def test_link_tag_using_post_javascript_and_popup assert_raise(ActionView::ActionViewError) { link_to("Hello", "http://www.example.com", :popup => true, :method => :post, :confirm => "Are you serious?") } end diff --git a/actionpack/test/tmp/.gitignore b/actionpack/test/tmp/.gitignore new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/actionpack/test/tmp/.gitignore |