diff options
Diffstat (limited to 'actionpack/test/controller')
46 files changed, 1538 insertions, 458 deletions
diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb index a714e8bbcc..01cafe1aca 100644 --- a/actionpack/test/controller/action_pack_assertions_test.rb +++ b/actionpack/test/controller/action_pack_assertions_test.rb @@ -71,6 +71,11 @@ class ActionPackAssertionsController < ActionController::Base render :text => "Hello!", :content_type => Mime::RSS end + def render_with_layout + @variable_for_layout = nil + render "test/hello_world", :layout => "layouts/standard" + end + def session_stuffing session['xmas'] = 'turkey' render :text => "ho ho ho" @@ -154,20 +159,6 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase assert_equal @response.body, 'request method: GET' end - def test_redirect_to_named_route - with_routing do |set| - set.draw do - match 'route_one', :to => 'action_pack_assertions#nothing', :as => :route_one - match ':controller/:action' - end - set.install_helpers - - process :redirect_to_named_route - assert_redirected_to 'http://test.host/route_one' - assert_redirected_to route_one_url - end - end - def test_string_constraint with_routing do |set| set.draw do @@ -347,7 +338,7 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase end def test_render_based_on_parameters - process :render_based_on_parameters, "name" => "David" + process :render_based_on_parameters, "GET", "name" => "David" assert_equal "Mr. David", @response.body end @@ -471,6 +462,18 @@ class AssertTemplateTest < ActionController::TestCase end end + def test_fails_with_wrong_layout + get :render_with_layout + assert_raise(ActiveSupport::TestCase::Assertion) do + assert_template :layout => "application" + end + end + + def test_passes_with_correct_layout + get :render_with_layout + assert_template :layout => "layouts/standard" + end + def test_assert_template_reset_between_requests get :hello_world assert_template 'test/hello_world' diff --git a/actionpack/test/controller/addresses_render_test.rb b/actionpack/test/controller/addresses_render_test.rb deleted file mode 100644 index c1cd22113d..0000000000 --- a/actionpack/test/controller/addresses_render_test.rb +++ /dev/null @@ -1,35 +0,0 @@ -require 'abstract_unit' -require 'logger' -require 'controller/fake_controllers' - -class Address - def Address.count(conditions = nil, join = nil) - nil - end - - def Address.find_all(arg1, arg2, arg3, arg4) - [] - end - - def self.find(*args) - [] - end -end - -class AddressesTest < ActionController::TestCase - tests AddressesController - - def setup - super - # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get - # a more accurate simulation of what happens in "real life". - @controller.logger = Logger.new(nil) - - @request.host = "www.nextangle.com" - end - - def test_list - get :list - assert_equal "We only need to get this far!", @response.body.chomp - end -end diff --git a/actionpack/test/controller/assert_select_test.rb b/actionpack/test/controller/assert_select_test.rb index 5eef8a32d7..3d667f0a2f 100644 --- a/actionpack/test/controller/assert_select_test.rb +++ b/actionpack/test/controller/assert_select_test.rb @@ -47,10 +47,6 @@ class AssertSelectTest < ActionController::TestCase render :text=>@content, :layout=>false, :content_type=>Mime::XML @content = nil end - - def rescue_action(e) - raise e - end end tests AssertSelectController @@ -135,6 +131,13 @@ class AssertSelectTest < ActionController::TestCase assert_raise(Assertion) { assert_select "pre", :html=>text } end + def test_strip_textarea + render_html %Q{<textarea>\n\nfoo\n</textarea>} + assert_select "textarea", "\nfoo\n" + render_html %Q{<textarea>\nfoo</textarea>} + assert_select "textarea", "foo" + end + def test_counts render_html %Q{<div id="1">foo</div><div id="2">foo</div>} assert_nothing_raised { assert_select "div", 2 } diff --git a/actionpack/test/controller/base_test.rb b/actionpack/test/controller/base_test.rb index 9c22a4e7e0..2d4083252e 100644 --- a/actionpack/test/controller/base_test.rb +++ b/actionpack/test/controller/base_test.rb @@ -1,5 +1,5 @@ require 'abstract_unit' -require 'logger' +require 'active_support/logger' require 'pp' # require 'pp' early to prevent hidden_methods from not picking up the pretty-print methods until too late # Provide some controller to run the tests on. @@ -40,29 +40,6 @@ class NonEmptyController < ActionController::Base end end -class MethodMissingController < ActionController::Base - hide_action :shouldnt_be_called - def shouldnt_be_called - raise "NO WAY!" - end - -protected - - def method_missing(selector) - render :text => selector.to_s - end -end - -class AnotherMethodMissingController < ActionController::Base - cattr_accessor :_exception - rescue_from Exception, :with => :_exception= - - protected - def method_missing(*attrs, &block) - super - end -end - class DefaultUrlOptionsController < ActionController::Base def from_view render :inline => "<%= #{params[:route]} %>" @@ -79,7 +56,7 @@ class UrlOptionsController < ActionController::Base end def url_options - super.merge(:host => 'www.override.com', :action => 'new', :locale => 'en') + super.merge(:host => 'www.override.com') end end @@ -106,7 +83,7 @@ class ControllerClassTests < ActiveSupport::TestCase end end -class ControllerInstanceTests < Test::Unit::TestCase +class ControllerInstanceTests < ActiveSupport::TestCase def setup @empty = EmptyController.new @contained = Submodule::ContainedEmptyController.new @@ -116,6 +93,12 @@ class ControllerInstanceTests < Test::Unit::TestCase Submodule::ContainedNonEmptyController.new] end + def test_performed? + assert !@empty.performed? + @empty.response_body = ["sweet"] + assert @empty.performed? + end + def test_action_methods @empty_controllers.each do |c| assert_equal Set.new, c.class.action_methods, "#{c.controller_path} should be empty!" @@ -142,13 +125,11 @@ class PerformActionTest < ActionController::TestCase # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get # a more accurate simulation of what happens in "real life". - @controller.logger = Logger.new(nil) + @controller.logger = ActiveSupport::Logger.new(nil) @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new @request.host = "www.nextangle.com" - - rescue_action_in_public! end def test_process_should_be_precise @@ -159,32 +140,10 @@ class PerformActionTest < ActionController::TestCase assert_equal exception.message, "The action 'non_existent' could not be found for EmptyController" end - def test_get_on_priv_should_show_selector - use_controller MethodMissingController - get :shouldnt_be_called - assert_response :success - assert_equal 'shouldnt_be_called', @response.body - end - - def test_method_missing_is_not_an_action_name - use_controller MethodMissingController - assert !@controller.__send__(:action_method?, 'method_missing') - - get :method_missing - assert_response :success - assert_equal 'method_missing', @response.body - end - - def test_method_missing_should_recieve_symbol - use_controller AnotherMethodMissingController - get :some_action - assert_kind_of NameError, @controller._exception - end - def test_get_on_hidden_should_fail use_controller NonEmptyController - assert_raise(ActionController::UnknownAction) { get :hidden_action } - assert_raise(ActionController::UnknownAction) { get :another_hidden_action } + assert_raise(AbstractController::ActionNotFound) { get :hidden_action } + assert_raise(AbstractController::ActionNotFound) { get :another_hidden_action } end end @@ -194,7 +153,22 @@ class UrlOptionsTest < ActionController::TestCase def setup super @request.host = 'www.example.com' - rescue_action_in_public! + end + + def test_url_for_query_params_included + rs = ActionDispatch::Routing::RouteSet.new + rs.draw do + match 'home' => 'pages#home' + end + + options = { + :action => "home", + :controller => "pages", + :only_path => true, + :params => { "token" => "secret" } + } + + assert_equal '/home?token=secret', rs.url_for(options) end def test_url_options_override @@ -206,9 +180,9 @@ class UrlOptionsTest < ActionController::TestCase get :from_view, :route => "from_view_url" - assert_equal 'http://www.override.com/from_view?locale=en', @response.body - assert_equal 'http://www.override.com/from_view?locale=en', @controller.send(:from_view_url) - assert_equal 'http://www.override.com/default_url_options/new?locale=en', @controller.url_for(:controller => 'default_url_options') + assert_equal 'http://www.override.com/from_view', @response.body + assert_equal 'http://www.override.com/from_view', @controller.send(:from_view_url) + assert_equal 'http://www.override.com/default_url_options/index', @controller.url_for(:controller => 'default_url_options') end end @@ -218,7 +192,6 @@ class UrlOptionsTest < ActionController::TestCase match "account/overview" end - @controller.class.send(:include, set.url_helpers) assert !@controller.class.action_methods.include?("account_overview_path") end end @@ -230,7 +203,6 @@ class DefaultUrlOptionsTest < ActionController::TestCase def setup super @request.host = 'www.example.com' - rescue_action_in_public! end def test_default_url_options_override @@ -281,7 +253,6 @@ class EmptyUrlOptionsTest < ActionController::TestCase def setup super @request.host = 'www.example.com' - rescue_action_in_public! end def test_ensure_url_for_works_as_expected_when_called_with_no_options_if_default_url_options_is_not_set diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb index da3314fe6d..a42c68a628 100644 --- a/actionpack/test/controller/caching_test.rb +++ b/actionpack/test/controller/caching_test.rb @@ -14,10 +14,14 @@ class CachingController < ActionController::Base end class PageCachingTestController < CachingController + self.page_cache_compression = :best_compression + caches_page :ok, :no_content, :if => Proc.new { |c| !c.request.format.json? } caches_page :found, :not_found caches_page :about_me - + caches_page :default_gzip + caches_page :no_gzip, :gzip => false + caches_page :gzip_level, :gzip => :best_speed def ok head :ok @@ -40,6 +44,18 @@ class PageCachingTestController < CachingController cache_page("Super soaker", "/index.html") end + def default_gzip + render :text => "Text" + end + + def no_gzip + render :text => "PNG" + end + + def gzip_level + render :text => "Big text" + end + def expire_custom_path expire_page("/index.html") head :ok @@ -115,6 +131,30 @@ class PageCachingTest < ActionController::TestCase assert !File.exist?("#{FILE_STORE_PATH}/index.html") end + def test_should_gzip_cache + get :custom_path + assert File.exist?("#{FILE_STORE_PATH}/index.html.gz") + + get :expire_custom_path + assert !File.exist?("#{FILE_STORE_PATH}/index.html.gz") + end + + def test_should_allow_to_disable_gzip + get :no_gzip + assert File.exist?("#{FILE_STORE_PATH}/page_caching_test/no_gzip.html") + assert !File.exist?("#{FILE_STORE_PATH}/page_caching_test/no_gzip.html.gz") + end + + def test_should_use_config_gzip_by_default + @controller.expects(:cache_page).with(nil, nil, Zlib::BEST_COMPRESSION) + get :default_gzip + end + + def test_should_set_gzip_level + @controller.expects(:cache_page).with(nil, nil, Zlib::BEST_SPEED) + get :gzip_level + end + def test_should_cache_without_trailing_slash_on_url @controller.class.cache_page 'cached content', '/page_caching_test/trailing_slash' assert File.exist?("#{FILE_STORE_PATH}/page_caching_test/trailing_slash.html") @@ -140,7 +180,7 @@ class PageCachingTest < ActionController::TestCase end [:ok, :no_content, :found, :not_found].each do |status| - [:get, :post, :put, :delete].each do |method| + [:get, :post, :patch, :put, :delete].each do |method| unless method == :get && status == :ok define_method "test_shouldnt_cache_#{method}_with_#{status}_status" do send(method, status) @@ -194,10 +234,12 @@ class ActionCachingTestController < CachingController caches_action :show, :cache_path => 'http://test.host/custom/show' caches_action :edit, :cache_path => Proc.new { |c| c.params[:id] ? "http://test.host/#{c.params[:id]};edit" : "http://test.host/edit" } caches_action :with_layout + caches_action :with_format_and_http_param, :cache_path => Proc.new { |c| { :key => 'value' } } caches_action :layout_false, :layout => false caches_action :record_not_found, :four_oh_four, :simple_runtime_error + caches_action :streaming - layout 'talk_from_action.erb' + layout 'talk_from_action' def index @cache_this = MockTime.now.to_f.to_s @@ -219,6 +261,11 @@ class ActionCachingTestController < CachingController render :text => @cache_this, :layout => true end + def with_format_and_http_param + @cache_this = MockTime.now.to_f.to_s + render :text => @cache_this + end + def record_not_found raise ActiveRecord::RecordNotFound, "oops!" end @@ -245,6 +292,15 @@ class ActionCachingTestController < CachingController expire_action :controller => 'action_caching_test', :action => 'index', :format => 'xml' render :nothing => true end + + def expire_with_url_string + expire_action url_for(:controller => 'action_caching_test', :action => 'index') + render :nothing => true + end + + def streaming + render :text => "streaming", :stream => true + end end class MockTime < Time @@ -359,6 +415,13 @@ class ActionCacheTest < ActionController::TestCase assert !fragment_exist?('hostname.com/action_caching_test') end + def test_action_cache_with_format_and_http_param + get :with_format_and_http_param, :format => 'json' + assert_response :success + assert !fragment_exist?('hostname.com/action_caching_test/with_format_and_http_param.json?key=value.json') + assert fragment_exist?('hostname.com/action_caching_test/with_format_and_http_param.json?key=value') + end + def test_action_cache_with_store_options MockTime.expects(:now).returns(12345).once @controller.expects(:read_fragment).with('hostname.com/action_caching_test', :expires_in => 1.hour).once @@ -432,6 +495,21 @@ class ActionCacheTest < ActionController::TestCase assert_not_equal cached_time, @response.body end + def test_cache_expiration_with_url_string + get :index + cached_time = content_to_cache + reset! + + @request.request_uri = "/action_caching_test/expire_with_url_string" + get :expire_with_url_string + assert_response :success + reset! + + get :index + assert_response :success + assert_not_equal cached_time, @response.body + end + def test_cache_is_scoped_by_subdomain @request.host = 'jamis.hostname.com' get :index @@ -574,6 +652,13 @@ class ActionCacheTest < ActionController::TestCase assert_response 500 end + def test_action_caching_plus_streaming + get :streaming + assert_response :success + assert_match(/streaming/, @response.body) + assert fragment_exist?('hostname.com/action_caching_test/streaming') + end + private def content_to_cache assigns(:cache_this) @@ -613,8 +698,6 @@ class FragmentCachingTest < ActionController::TestCase @controller.params = @params @controller.request = @request @controller.response = @response - @controller.send(:initialize_template_class, @response) - @controller.send(:assign_shortcuts, @request, @response) end def test_fragment_cache_key @@ -722,10 +805,6 @@ class FunctionalCachingController < CachingController format.xml end end - - def rescue_action(e) - raise e - end end class FunctionalFragmentCachingTest < ActionController::TestCase @@ -745,6 +824,7 @@ class FunctionalFragmentCachingTest < ActionController::TestCase expected_body = <<-CACHED Hello This bit's fragment cached +Ciao CACHED assert_equal expected_body, @response.body @@ -786,3 +866,51 @@ CACHED assert_equal " <p>Builder</p>\n", @store.read('views/test.host/functional_caching/formatted_fragment_cached') end end + +class CacheHelperOutputBufferTest < ActionController::TestCase + + class MockController + def read_fragment(name, options) + return false + end + + def write_fragment(name, fragment, options) + fragment + end + end + + def setup + super + end + + def test_output_buffer + output_buffer = ActionView::OutputBuffer.new + controller = MockController.new + cache_helper = Object.new + cache_helper.extend(ActionView::Helpers::CacheHelper) + cache_helper.expects(:controller).returns(controller).at_least(0) + cache_helper.expects(:output_buffer).returns(output_buffer).at_least(0) + # if the output_buffer is changed, the new one should be html_safe and of the same type + cache_helper.expects(:output_buffer=).with(responds_with(:html_safe?, true)).with(instance_of(output_buffer.class)).at_least(0) + + assert_nothing_raised do + cache_helper.send :fragment_for, 'Test fragment name', 'Test fragment', &Proc.new{ nil } + end + end + + def test_safe_buffer + output_buffer = ActiveSupport::SafeBuffer.new + controller = MockController.new + cache_helper = Object.new + cache_helper.extend(ActionView::Helpers::CacheHelper) + cache_helper.expects(:controller).returns(controller).at_least(0) + cache_helper.expects(:output_buffer).returns(output_buffer).at_least(0) + # if the output_buffer is changed, the new one should be html_safe and of the same type + cache_helper.expects(:output_buffer=).with(responds_with(:html_safe?, true)).with(instance_of(output_buffer.class)).at_least(0) + + assert_nothing_raised do + cache_helper.send :fragment_for, 'Test fragment name', 'Test fragment', &Proc.new{ nil } + end + end + +end diff --git a/actionpack/test/controller/capture_test.rb b/actionpack/test/controller/capture_test.rb index d78acb8ce8..72263156d9 100644 --- a/actionpack/test/controller/capture_test.rb +++ b/actionpack/test/controller/capture_test.rb @@ -1,5 +1,5 @@ require 'abstract_unit' -require 'logger' +require 'active_support/logger' class CaptureController < ActionController::Base def self.controller_name; "test"; end @@ -28,8 +28,6 @@ class CaptureController < ActionController::Base def proper_block_detection @todo = "some todo" end - - def rescue_action(e) raise end end class CaptureTest < ActionController::TestCase @@ -39,7 +37,7 @@ class CaptureTest < ActionController::TestCase super # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get # a more accurate simulation of what happens in "real life". - @controller.logger = Logger.new(nil) + @controller.logger = ActiveSupport::Logger.new(nil) @request.host = "www.nextangle.com" end diff --git a/actionpack/test/controller/content_type_test.rb b/actionpack/test/controller/content_type_test.rb index d51882066d..03d5d27cf4 100644 --- a/actionpack/test/controller/content_type_test.rb +++ b/actionpack/test/controller/content_type_test.rb @@ -48,8 +48,6 @@ class OldContentTypeController < ActionController::Base format.rss { render :text => "hello world!", :content_type => Mime::XML } end end - - def rescue_action(e) raise end end class ContentTypeTest < ActionController::TestCase @@ -59,7 +57,7 @@ class ContentTypeTest < ActionController::TestCase super # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get # a more accurate simulation of what happens in "real life". - @controller.logger = Logger.new(nil) + @controller.logger = ActiveSupport::Logger.new(nil) end # :ported: @@ -70,12 +68,12 @@ class ContentTypeTest < ActionController::TestCase end def test_render_changed_charset_default - OldContentTypeController.default_charset = "utf-16" + ActionDispatch::Response.default_charset = "utf-16" get :render_defaults assert_equal "utf-16", @response.charset assert_equal Mime::HTML, @response.content_type ensure - OldContentTypeController.default_charset = "utf-8" + ActionDispatch::Response.default_charset = "utf-8" end # :ported: @@ -107,12 +105,12 @@ class ContentTypeTest < ActionController::TestCase end def test_nil_default_for_erb - OldContentTypeController.default_charset = nil + ActionDispatch::Response.default_charset = nil get :render_default_for_erb assert_equal Mime::HTML, @response.content_type assert_nil @response.charset, @response.headers.inspect ensure - OldContentTypeController.default_charset = "utf-8" + ActionDispatch::Response.default_charset = "utf-8" end def test_default_for_erb diff --git a/actionpack/test/controller/default_url_options_with_filter_test.rb b/actionpack/test/controller/default_url_options_with_filter_test.rb index 3bbb981040..ef028e8cdb 100644 --- a/actionpack/test/controller/default_url_options_with_filter_test.rb +++ b/actionpack/test/controller/default_url_options_with_filter_test.rb @@ -21,7 +21,7 @@ end class ControllerWithBeforeFilterAndDefaultUrlOptionsTest < ActionController::TestCase - # This test has it´s roots in issue #1872 + # This test has its roots in issue #1872 test "should redirect with correct locale :de" do get :redirect, :locale => "de" assert_redirected_to "/controller_with_before_filter_and_default_url_options/target?locale=de" diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb index d5e3da4d88..65c853f6eb 100644 --- a/actionpack/test/controller/filters_test.rb +++ b/actionpack/test/controller/filters_test.rb @@ -16,7 +16,7 @@ class ActionController::Base def assigns(key = nil) assigns = {} - instance_variable_names.each do |ivar| + instance_variables.each do |ivar| next if ActionController::Base.protected_instance_variables.include?(ivar) assigns[ivar[1..-1]] = instance_variable_get(ivar) end @@ -165,8 +165,6 @@ class FilterTest < ActionController::TestCase @ran_filter ||= [] @ran_filter << "clean_up_tmp" end - - def rescue_action(e) raise(e) end end class ConditionalCollectionFilterController < ConditionalFilterController @@ -454,11 +452,6 @@ class FilterTest < ActionController::TestCase def show raise ErrorToRescue.new("Something made the bad noise.") end - - private - def rescue_action(exception) - raise exception - end end class NonYieldingAroundFilterController < ActionController::Base @@ -472,9 +465,6 @@ class FilterTest < ActionController::TestCase render :inline => "index" end - #make sure the controller complains - def rescue_action(e); raise e; end - private def filter_one @@ -825,11 +815,7 @@ class FilterTest < ActionController::TestCase end end - - class PostsController < ActionController::Base - def rescue_action(e); raise e; end - module AroundExceptions class Error < StandardError ; end class Before < Error ; end @@ -951,9 +937,7 @@ class ControllerWithAllTypesOfFilters < PostsController end class ControllerWithTwoLessFilters < ControllerWithAllTypesOfFilters - $vbf = true skip_filter :around_again - $vbf = false skip_filter :after end diff --git a/actionpack/test/controller/flash_hash_test.rb b/actionpack/test/controller/flash_hash_test.rb index 9b69a2648e..ccca0dac17 100644 --- a/actionpack/test/controller/flash_hash_test.rb +++ b/actionpack/test/controller/flash_hash_test.rb @@ -75,6 +75,7 @@ module ActionDispatch def test_discard_no_args @hash['hello'] = 'world' @hash.discard + @hash.sweep assert_equal({}, @hash.to_hash) end @@ -83,8 +84,88 @@ module ActionDispatch @hash['hello'] = 'world' @hash['omg'] = 'world' @hash.discard 'hello' + @hash.sweep assert_equal({'omg' => 'world'}, @hash.to_hash) end + + def test_keep_sweep + @hash['hello'] = 'world' + + @hash.sweep + assert_equal({'hello' => 'world'}, @hash.to_hash) + end + + def test_update_sweep + @hash['hello'] = 'world' + @hash.update({'hi' => 'mom'}) + + @hash.sweep + assert_equal({'hello' => 'world', 'hi' => 'mom'}, @hash.to_hash) + end + + def test_update_delete_sweep + @hash['hello'] = 'world' + @hash.delete 'hello' + @hash.update({'hello' => 'mom'}) + + @hash.sweep + assert_equal({'hello' => 'mom'}, @hash.to_hash) + end + + def test_delete_sweep + @hash['hello'] = 'world' + @hash['hi'] = 'mom' + @hash.delete 'hi' + + @hash.sweep + assert_equal({'hello' => 'world'}, @hash.to_hash) + end + + def test_clear_sweep + @hash['hello'] = 'world' + @hash.clear + + @hash.sweep + assert_equal({}, @hash.to_hash) + end + + def test_replace_sweep + @hash['hello'] = 'world' + @hash.replace({'hi' => 'mom'}) + + @hash.sweep + assert_equal({'hi' => 'mom'}, @hash.to_hash) + end + + def test_discard_then_add + @hash['hello'] = 'world' + @hash['omg'] = 'world' + @hash.discard 'hello' + @hash['hello'] = 'world' + + @hash.sweep + assert_equal({'omg' => 'world', 'hello' => 'world'}, @hash.to_hash) + end + + def test_keep_all_sweep + @hash['hello'] = 'world' + @hash['omg'] = 'world' + @hash.discard 'hello' + @hash.keep + + @hash.sweep + assert_equal({'omg' => 'world', 'hello' => 'world'}, @hash.to_hash) + end + + def test_double_sweep + @hash['hello'] = 'world' + @hash.sweep + + assert_equal({'hello' => 'world'}, @hash.to_hash) + + @hash.sweep + assert_equal({}, @hash.to_hash) + end end end diff --git a/actionpack/test/controller/flash_test.rb b/actionpack/test/controller/flash_test.rb index e19612eace..37ccc7a4a5 100644 --- a/actionpack/test/controller/flash_test.rb +++ b/actionpack/test/controller/flash_test.rb @@ -51,10 +51,6 @@ class FlashTest < ActionController::TestCase render :inline => "hello" end - def rescue_action(e) - raise unless ActionView::MissingTemplate === e - end - # methods for test_sweep_after_halted_filter_chain before_filter :halt_and_redir, :only => "filter_halting_action" @@ -254,16 +250,6 @@ class FlashIntegrationTest < ActionDispatch::IntegrationTest end end - def test_setting_flash_raises_after_stream_back_to_client - with_test_route_set do - env = { 'action_dispatch.request.flash_hash' => ActionDispatch::Flash::FlashHash.new } - get '/set_flash', nil, env - assert_raise(ActionDispatch::ClosedError) { - @request.flash['alert'] = 'alert' - } - end - end - def test_setting_flash_does_not_raise_in_following_requests with_test_route_set do env = { 'action_dispatch.request.flash_hash' => ActionDispatch::Flash::FlashHash.new } @@ -280,36 +266,6 @@ class FlashIntegrationTest < ActionDispatch::IntegrationTest end end - def test_setting_flash_raises_after_stream_back_to_client_even_with_an_empty_flash - with_test_route_set do - env = { 'action_dispatch.request.flash_hash' => ActionDispatch::Flash::FlashHash.new } - get '/dont_set_flash', nil, env - assert_raise(ActionDispatch::ClosedError) { - @request.flash['alert'] = 'alert' - } - end - end - - def test_setting_flash_now_raises_after_stream_back_to_client - with_test_route_set do - env = { 'action_dispatch.request.flash_hash' => ActionDispatch::Flash::FlashHash.new } - get '/set_flash_now', nil, env - assert_raise(ActionDispatch::ClosedError) { - @request.flash.now['alert'] = 'alert' - } - end - end - - def test_setting_flash_now_raises_after_stream_back_to_client_even_with_an_empty_flash - with_test_route_set do - env = { 'action_dispatch.request.flash_hash' => ActionDispatch::Flash::FlashHash.new } - get '/dont_set_flash', nil, env - assert_raise(ActionDispatch::ClosedError) { - @request.flash.now['alert'] = 'alert' - } - end - end - private # Overwrite get to send SessionSecret in env hash diff --git a/actionpack/test/controller/force_ssl_test.rb b/actionpack/test/controller/force_ssl_test.rb index 3e723e20d9..5b423c8151 100644 --- a/actionpack/test/controller/force_ssl_test.rb +++ b/actionpack/test/controller/force_ssl_test.rb @@ -14,6 +14,10 @@ class ForceSSLControllerLevel < ForceSSLController force_ssl end +class ForceSSLCustomDomain < ForceSSLController + force_ssl :host => "secure.test.host" +end + class ForceSSLOnlyAction < ForceSSLController force_ssl :only => :cheeseburger end @@ -22,6 +26,29 @@ class ForceSSLExceptAction < ForceSSLController force_ssl :except => :banana end +class ForceSSLIfCondition < ForceSSLController + force_ssl :if => :use_force_ssl? + + def use_force_ssl? + action_name == 'cheeseburger' + end +end + +class ForceSSLFlash < ForceSSLController + force_ssl :except => [:banana, :set_flash, :use_flash] + + def set_flash + flash["that"] = "hello" + redirect_to '/force_ssl_flash/cheeseburger' + end + + def use_flash + @flash_copy = {}.update flash + @flashy = flash["that"] + render :inline => "hello" + end +end + class ForceSSLControllerLevelTest < ActionController::TestCase tests ForceSSLControllerLevel @@ -31,6 +58,12 @@ class ForceSSLControllerLevelTest < ActionController::TestCase assert_equal "https://test.host/force_ssl_controller_level/banana", redirect_to_url end + def test_banana_redirects_to_https_with_extra_params + get :banana, :token => "secret" + assert_response 301 + assert_equal "https://test.host/force_ssl_controller_level/banana?token=secret", redirect_to_url + end + def test_cheeseburger_redirects_to_https get :cheeseburger assert_response 301 @@ -38,6 +71,22 @@ class ForceSSLControllerLevelTest < ActionController::TestCase end end +class ForceSSLCustomDomainTest < ActionController::TestCase + tests ForceSSLCustomDomain + + def test_banana_redirects_to_https_with_custom_host + get :banana + assert_response 301 + assert_equal "https://secure.test.host/force_ssl_custom_domain/banana", redirect_to_url + end + + def test_cheeseburger_redirects_to_https_with_custom_host + get :cheeseburger + assert_response 301 + assert_equal "https://secure.test.host/force_ssl_custom_domain/cheeseburger", redirect_to_url + end +end + class ForceSSLOnlyActionTest < ActionController::TestCase tests ForceSSLOnlyAction @@ -68,16 +117,35 @@ class ForceSSLExceptActionTest < ActionController::TestCase end end -class ForceSSLExcludeDevelopmentTest < ActionController::TestCase - tests ForceSSLControllerLevel - - def setup - Rails.env.stubs(:development?).returns(false) - end +class ForceSSLIfConditionTest < ActionController::TestCase + tests ForceSSLIfCondition - def test_development_environment_not_redirects_to_https - Rails.env.stubs(:development?).returns(true) + def test_banana_not_redirects_to_https get :banana assert_response 200 end -end
\ No newline at end of file + + def test_cheeseburger_redirects_to_https + get :cheeseburger + assert_response 301 + assert_equal "https://test.host/force_ssl_if_condition/cheeseburger", redirect_to_url + end +end + +class ForceSSLFlashTest < ActionController::TestCase + tests ForceSSLFlash + + def test_cheeseburger_redirects_to_https + get :set_flash + assert_response 302 + assert_equal "http://test.host/force_ssl_flash/cheeseburger", redirect_to_url + + get :cheeseburger + assert_response 301 + assert_equal "https://test.host/force_ssl_flash/cheeseburger", redirect_to_url + + get :use_flash + assert_equal "hello", assigns["flash_copy"]["that"] + assert_equal "hello", assigns["flashy"] + end +end diff --git a/actionpack/test/controller/helper_test.rb b/actionpack/test/controller/helper_test.rb index 35a87c1aae..757661d8d0 100644 --- a/actionpack/test/controller/helper_test.rb +++ b/actionpack/test/controller/helper_test.rb @@ -7,16 +7,12 @@ module Fun def render_hello_world render :inline => "hello: <%= stratego %>" end - - def rescue_action(e) raise end end class PdfController < ActionController::Base def test render :inline => "test: <%= foobar %>" end - - def rescue_action(e) raise end end end @@ -60,7 +56,6 @@ class HelperTest < ActiveSupport::TestCase class TestController < ActionController::Base attr_accessor :delegate_attr def delegate_method() end - def rescue_action(e) raise end end def setup @@ -201,8 +196,6 @@ class IsolatedHelpersTest < ActiveSupport::TestCase def index render :inline => '<%= shout %>' end - - def rescue_action(e) raise end end class B < A diff --git a/actionpack/test/controller/http_basic_authentication_test.rb b/actionpack/test/controller/http_basic_authentication_test.rb index 364e96d4f6..7286b249c7 100644 --- a/actionpack/test/controller/http_basic_authentication_test.rb +++ b/actionpack/test/controller/http_basic_authentication_test.rb @@ -132,6 +132,6 @@ class HttpBasicAuthenticationTest < ActionController::TestCase private def encode_credentials(username, password) - "Basic #{ActiveSupport::Base64.encode64("#{username}:#{password}")}" + "Basic #{::Base64.encode64("#{username}:#{password}")}" end end diff --git a/actionpack/test/controller/http_digest_authentication_test.rb b/actionpack/test/controller/http_digest_authentication_test.rb index b011536717..828ea5b0fb 100644 --- a/actionpack/test/controller/http_digest_authentication_test.rb +++ b/actionpack/test/controller/http_digest_authentication_test.rb @@ -139,7 +139,7 @@ class HttpDigestAuthenticationTest < ActionController::TestCase test "authentication request with request-uri that doesn't match credentials digest-uri" do @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please') - @request.env['PATH_INFO'] = "/http_digest_authentication_test/dummy_digest/altered/uri" + @request.env['ORIGINAL_FULLPATH'] = "/http_digest_authentication_test/dummy_digest/altered/uri" get :display assert_response :unauthorized @@ -208,6 +208,44 @@ class HttpDigestAuthenticationTest < ActionController::TestCase assert !ActionController::HttpAuthentication::Digest.validate_digest_response(@request, "SuperSecret"){nil} end + test "authentication request with request-uri ending in '/'" do + @request.env['PATH_INFO'] = "/http_digest_authentication_test/dummy_digest/" + @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please') + + # simulate normalizing PATH_INFO + @request.env['PATH_INFO'] = "/http_digest_authentication_test/dummy_digest" + get :display + + assert_response :success + assert_equal 'Definitely Maybe', @response.body + end + + test "authentication request with request-uri ending in '?'" do + @request.env['PATH_INFO'] = "/http_digest_authentication_test/dummy_digest/?" + @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please') + + # simulate normalizing PATH_INFO + @request.env['PATH_INFO'] = "/http_digest_authentication_test/dummy_digest" + get :display + + assert_response :success + assert_equal 'Definitely Maybe', @response.body + end + + test "authentication request with absolute uri in credentials (as in IE) ending with /" do + @request.env['PATH_INFO'] = "/http_digest_authentication_test/dummy_digest/" + @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:uri => "http://test.host/http_digest_authentication_test/dummy_digest/", + :username => 'pretty', :password => 'please') + + # simulate normalizing PATH_INFO + @request.env['PATH_INFO'] = "/http_digest_authentication_test/dummy_digest" + get :display + + assert_response :success + assert assigns(:logged_in) + assert_equal 'Definitely Maybe', @response.body + end + private def encode_credentials(options) @@ -228,11 +266,14 @@ class HttpDigestAuthenticationTest < ActionController::TestCase credentials = decode_credentials(@response.headers['WWW-Authenticate']) credentials.merge!(options) - credentials.merge!(:uri => @request.env['PATH_INFO'].to_s) + path_info = @request.env['PATH_INFO'].to_s + uri = options[:uri] || path_info + credentials.merge!(:uri => uri) + @request.env["ORIGINAL_FULLPATH"] = path_info ActionController::HttpAuthentication::Digest.encode_credentials(method, credentials, password, options[:password_is_ha1]) end def decode_credentials(header) - ActionController::HttpAuthentication::Digest.decode_credentials(@response.headers['WWW-Authenticate']) + ActionController::HttpAuthentication::Digest.decode_credentials(header) end end diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb index 23709e44e2..44f033119d 100644 --- a/actionpack/test/controller/integration_test.rb +++ b/actionpack/test/controller/integration_test.rb @@ -2,7 +2,7 @@ require 'abstract_unit' require 'controller/fake_controllers' require 'action_controller/vendor/html-scanner' -class SessionTest < Test::Unit::TestCase +class SessionTest < ActiveSupport::TestCase StubApp = lambda { |env| [200, {"Content-Type" => "text/html", "Content-Length" => "13"}, ["Hello, World!"]] } @@ -63,6 +63,12 @@ class SessionTest < Test::Unit::TestCase @session.post_via_redirect(path, args, headers) end + def test_patch_via_redirect + path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue" } + @session.expects(:request_via_redirect).with(:patch, path, args, headers) + @session.patch_via_redirect(path, args, headers) + end + def test_put_via_redirect path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue" } @session.expects(:request_via_redirect).with(:put, path, args, headers) @@ -87,6 +93,12 @@ class SessionTest < Test::Unit::TestCase @session.post(path,params,headers) end + def test_patch + path = "/index"; params = "blah"; headers = {:location => 'blah'} + @session.expects(:process).with(:patch,path,params,headers) + @session.patch(path,params,headers) + end + def test_put path = "/index"; params = "blah"; headers = {:location => 'blah'} @session.expects(:process).with(:put,path,params,headers) @@ -105,6 +117,12 @@ class SessionTest < Test::Unit::TestCase @session.head(path,params,headers) end + def test_options + path = "/index"; params = "blah"; headers = {:location => 'blah'} + @session.expects(:process).with(:options,path,params,headers) + @session.options(path,params,headers) + end + def test_xml_http_request_get path = "/index"; params = "blah"; headers = {:location => 'blah'} headers_after_xhr = headers.merge( @@ -125,6 +143,16 @@ class SessionTest < Test::Unit::TestCase @session.xml_http_request(:post,path,params,headers) end + def test_xml_http_request_patch + path = "/index"; params = "blah"; headers = {:location => 'blah'} + headers_after_xhr = headers.merge( + "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest", + "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*" + ) + @session.expects(:process).with(:patch,path,params,headers_after_xhr) + @session.xml_http_request(:patch,path,params,headers) + end + def test_xml_http_request_put path = "/index"; params = "blah"; headers = {:location => 'blah'} headers_after_xhr = headers.merge( @@ -155,6 +183,16 @@ class SessionTest < Test::Unit::TestCase @session.xml_http_request(:head,path,params,headers) end + def test_xml_http_request_options + path = "/index"; params = "blah"; headers = {:location => 'blah'} + headers_after_xhr = headers.merge( + "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest", + "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*" + ) + @session.expects(:process).with(:options,path,params,headers_after_xhr) + @session.xml_http_request(:options,path,params,headers) + end + def test_xml_http_request_override_accept path = "/index"; params = "blah"; headers = {:location => 'blah', "HTTP_ACCEPT" => "application/xml"} headers_after_xhr = headers.merge( @@ -165,7 +203,7 @@ class SessionTest < Test::Unit::TestCase end end -class IntegrationTestTest < Test::Unit::TestCase +class IntegrationTestTest < ActiveSupport::TestCase def setup @test = ::ActionDispatch::IntegrationTest.new(:app) @test.class.stubs(:fixture_table_names).returns([]) @@ -212,7 +250,7 @@ class IntegrationTestUsesCorrectClass < ActionDispatch::IntegrationTest @integration_session.stubs(:generic_url_rewriter) @integration_session.stubs(:process) - %w( get post head put delete ).each do |verb| + %w( get post head patch put delete options ).each do |verb| assert_nothing_raised("'#{verb}' should use integration test methods") { __send__(verb, '/') } end end @@ -493,7 +531,7 @@ class ApplicationIntegrationTest < ActionDispatch::IntegrationTest routes.draw do match '', :to => 'application_integration_test/test#index', :as => :empty_string - + match 'foo', :to => 'application_integration_test/test#index', :as => :foo match 'bar', :to => 'application_integration_test/test#index', :as => :bar end @@ -511,7 +549,7 @@ class ApplicationIntegrationTest < ActionDispatch::IntegrationTest test "route helpers after controller access" do get '/' assert_equal '/', empty_string_path - + get '/foo' assert_equal '/foo', foo_path @@ -528,11 +566,43 @@ class ApplicationIntegrationTest < ActionDispatch::IntegrationTest assert_raise(NameError) { missing_path } end - test "process reuse the env we pass as argument" do + test "process do not modify the env passed as argument" do env = { :SERVER_NAME => 'server', 'action_dispatch.custom' => 'custom' } + old_env = env.dup get '/foo', nil, env - assert_equal :get, env[:method] - assert_equal 'server', env[:SERVER_NAME] - assert_equal 'custom', env['action_dispatch.custom'] + assert_equal old_env, env + end +end + +class EnvironmentFilterIntegrationTest < ActionDispatch::IntegrationTest + class TestController < ActionController::Base + def post + render :text => "Created", :status => 201 + end + end + + def self.call(env) + env["action_dispatch.parameter_filter"] = [:password] + routes.call(env) + end + + def self.routes + @routes ||= ActionDispatch::Routing::RouteSet.new + end + + routes.draw do + match '/post', :to => 'environment_filter_integration_test/test#post', :via => :post + end + + def app + self.class + end + + test "filters rack request form vars" do + post "/post", :username => 'cjolly', :password => 'secret' + + assert_equal 'cjolly', request.filtered_parameters['username'] + assert_equal '[FILTERED]', request.filtered_parameters['password'] + assert_equal '[FILTERED]', request.filtered_env['rack.request.form_vars'] end end diff --git a/actionpack/test/controller/layout_test.rb b/actionpack/test/controller/layout_test.rb index cafe2b9320..c73b36f05e 100644 --- a/actionpack/test/controller/layout_test.rb +++ b/actionpack/test/controller/layout_test.rb @@ -78,8 +78,15 @@ end class DefaultLayoutController < LayoutTest end +class StreamingLayoutController < LayoutTest + def render(*args) + options = args.extract_options! || {} + super(*args, options.merge(:stream => true)) + end +end + class AbsolutePathLayoutController < LayoutTest - layout File.expand_path(File.expand_path(__FILE__) + '/../../fixtures/layout_tests/layouts/layout_test.erb') + layout File.expand_path(File.expand_path(__FILE__) + '/../../fixtures/layout_tests/layouts/layout_test') end class HasOwnLayoutController < LayoutTest @@ -122,6 +129,12 @@ class LayoutSetInResponseTest < ActionController::TestCase assert_template :layout => "layouts/layout_test" end + def test_layout_set_when_using_streaming_layout + @controller = StreamingLayoutController.new + get :hello + assert_template :hello + end + def test_layout_set_when_set_in_controller @controller = HasOwnLayoutController.new get :hello @@ -167,7 +180,7 @@ class LayoutSetInResponseTest < ActionController::TestCase def test_layout_is_picked_from_the_controller_instances_view_path @controller = PrependsViewPathController.new get :hello - assert_template :layout => /layouts\/alt\.\w+/ + assert_template :layout => /layouts\/alt/ end def test_absolute_pathed_layout @@ -184,7 +197,7 @@ class RenderWithTemplateOptionController < LayoutTest end class SetsNonExistentLayoutFile < LayoutTest - layout "nofile.erb" + layout "nofile" end class LayoutExceptionRaised < ActionController::TestCase diff --git a/actionpack/test/controller/log_subscriber_test.rb b/actionpack/test/controller/log_subscriber_test.rb index ccdfcb0b2c..700fd788fa 100644 --- a/actionpack/test/controller/log_subscriber_test.rb +++ b/actionpack/test/controller/log_subscriber_test.rb @@ -13,6 +13,11 @@ module Another head :status => 406 end + before_filter :redirector, :only => :never_executed + + def never_executed + end + def show render :nothing => true end @@ -49,7 +54,6 @@ module Another def with_rescued_exception raise SpecialException end - end end @@ -86,6 +90,13 @@ class ACLogSubscriberTest < ActionController::TestCase assert_equal "Processing by Another::LogSubscribersController#show as HTML", logs.first end + def test_halted_callback + get :never_executed + wait + assert_equal 4, logs.size + assert_equal "Filter chain halted as :redirector rendered or redirected", logs.third + end + def test_process_action get :show wait diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb index afb2d39955..0e4099ddc6 100644 --- a/actionpack/test/controller/mime_responds_test.rb +++ b/actionpack/test/controller/mime_responds_test.rb @@ -132,7 +132,6 @@ class RespondToController < ActionController::Base end end - def iphone_with_html_response_type request.format = :iphone if request.env["HTTP_ACCEPT"] == "text/iphone" @@ -151,10 +150,6 @@ class RespondToController < ActionController::Base end end - def rescue_action(e) - raise - end - protected def set_layout if action_name.in?(["all_types_with_layout", "iphone_with_html_response_type"]) @@ -498,7 +493,7 @@ class RespondToControllerTest < ActionController::TestCase assert_equal '<html><div id="iphone">Hello iPhone future from iPhone!</div></html>', @response.body assert_equal "text/html", @response.content_type end - + def test_invalid_format get :using_defaults, :format => "invalidformat" assert_equal " ", @response.body @@ -509,7 +504,7 @@ end class RespondWithController < ActionController::Base respond_to :html, :json respond_to :xml, :except => :using_resource_with_block - respond_to :js, :only => [ :using_resource_with_block, :using_resource, :using_hash_resource ] + respond_to :js, :only => [ :using_resource_with_block, :using_resource, 'using_hash_resource' ] def using_resource respond_with(resource) @@ -597,6 +592,19 @@ class RenderJsonRespondWithController < RespondWithController format.json { render :json => RenderJsonTestException.new('boom') } end end + + def create + resource = ValidatedCustomer.new(params[:name], 1) + respond_with(resource) do |format| + format.json do + if resource.errors.empty? + render :json => { :valid => true } + else + render :json => { :valid => false } + end + end + end + end end class EmptyRespondWithController < ActionController::Base @@ -656,7 +664,9 @@ class RespondWithControllerTest < ActionController::TestCase @request.accept = "application/json" get :using_hash_resource assert_equal "application/json", @response.content_type - assert_equal %Q[{"result":{"name":"david","id":13}}], @response.body + assert @response.body.include?("result") + assert @response.body.include?('"name":"david"') + assert @response.body.include?('"id":13') end def test_using_hash_resource_with_post @@ -745,6 +755,55 @@ class RespondWithControllerTest < ActionController::TestCase end end + def test_using_resource_for_post_with_json_yields_unprocessable_entity_on_failure + with_test_route_set do + @request.accept = "application/json" + errors = { :name => :invalid } + Customer.any_instance.stubs(:errors).returns(errors) + post :using_resource + assert_equal "application/json", @response.content_type + assert_equal 422, @response.status + errors = {:errors => errors} + assert_equal errors.to_json, @response.body + assert_nil @response.location + end + end + + def test_using_resource_for_patch_with_html_redirects_on_success + with_test_route_set do + patch :using_resource + assert_equal "text/html", @response.content_type + assert_equal 302, @response.status + assert_equal "http://www.example.com/customers/13", @response.location + assert @response.redirect? + end + end + + def test_using_resource_for_patch_with_html_rerender_on_failure + with_test_route_set do + errors = { :name => :invalid } + Customer.any_instance.stubs(:errors).returns(errors) + patch :using_resource + assert_equal "text/html", @response.content_type + assert_equal 200, @response.status + assert_equal "Edit world!\n", @response.body + assert_nil @response.location + end + end + + def test_using_resource_for_patch_with_html_rerender_on_failure_even_on_method_override + with_test_route_set do + errors = { :name => :invalid } + Customer.any_instance.stubs(:errors).returns(errors) + @request.env["rack.methodoverride.original_method"] = "POST" + patch :using_resource + assert_equal "text/html", @response.content_type + assert_equal 200, @response.status + assert_equal "Edit world!\n", @response.body + assert_nil @response.location + end + end + def test_using_resource_for_put_with_html_redirects_on_success with_test_route_set do put :using_resource @@ -780,21 +839,21 @@ class RespondWithControllerTest < ActionController::TestCase end end - def test_using_resource_for_put_with_xml_yields_ok_on_success + def test_using_resource_for_put_with_xml_yields_no_content_on_success @request.accept = "application/xml" put :using_resource assert_equal "application/xml", @response.content_type - assert_equal 200, @response.status + assert_equal 204, @response.status assert_equal " ", @response.body end - def test_using_resource_for_put_with_json_yields_ok_on_success + def test_using_resource_for_put_with_json_yields_no_content_on_success Customer.any_instance.stubs(:to_json).returns('{"name": "David"}') @request.accept = "application/json" put :using_resource assert_equal "application/json", @response.content_type - assert_equal 200, @response.status - assert_equal "{}", @response.body + assert_equal 204, @response.status + assert_equal " ", @response.body end def test_using_resource_for_put_with_xml_yields_unprocessable_entity_on_failure @@ -808,6 +867,18 @@ class RespondWithControllerTest < ActionController::TestCase assert_nil @response.location end + def test_using_resource_for_put_with_json_yields_unprocessable_entity_on_failure + @request.accept = "application/json" + errors = { :name => :invalid } + Customer.any_instance.stubs(:errors).returns(errors) + put :using_resource + assert_equal "application/json", @response.content_type + assert_equal 422, @response.status + errors = {:errors => errors} + assert_equal errors.to_json, @response.body + assert_nil @response.location + end + def test_using_resource_for_delete_with_html_redirects_on_success with_test_route_set do Customer.any_instance.stubs(:destroyed?).returns(true) @@ -818,23 +889,23 @@ class RespondWithControllerTest < ActionController::TestCase end end - def test_using_resource_for_delete_with_xml_yields_ok_on_success + def test_using_resource_for_delete_with_xml_yields_no_content_on_success Customer.any_instance.stubs(:destroyed?).returns(true) @request.accept = "application/xml" delete :using_resource assert_equal "application/xml", @response.content_type - assert_equal 200, @response.status + assert_equal 204, @response.status assert_equal " ", @response.body end - def test_using_resource_for_delete_with_json_yields_ok_on_success + def test_using_resource_for_delete_with_json_yields_no_content_on_success Customer.any_instance.stubs(:to_json).returns('{"name": "David"}') Customer.any_instance.stubs(:destroyed?).returns(true) @request.accept = "application/json" delete :using_resource assert_equal "application/json", @response.content_type - assert_equal 200, @response.status - assert_equal "{}", @response.body + assert_equal 204, @response.status + assert_equal " ", @response.body end def test_using_resource_for_delete_with_html_redirects_on_failure @@ -940,6 +1011,18 @@ class RespondWithControllerTest < ActionController::TestCase assert_match(/"error":"RenderJsonTestException"/, @response.body) end + def test_api_response_with_valid_resource_respect_override_block + @controller = RenderJsonRespondWithController.new + post :create, :name => "sikachu", :format => :json + assert_equal '{"valid":true}', @response.body + end + + def test_api_response_with_invalid_resource_respect_override_block + @controller = RenderJsonRespondWithController.new + post :create, :name => "david", :format => :json + assert_equal '{"valid":false}', @response.body + end + def test_no_double_render_is_raised @request.accept = "text/html" assert_raise ActionView::MissingTemplate do @@ -1051,7 +1134,7 @@ class PostController < AbstractPostController around_filter :with_iphone def index - respond_to(:html, :iphone) + respond_to(:html, :iphone, :js) end protected @@ -1098,4 +1181,45 @@ class MimeControllerLayoutsTest < ActionController::TestCase get :index assert_equal '<html><div id="super_iphone">Super iPhone</div></html>', @response.body end + + def test_non_navigational_format_with_no_template_fallbacks_to_html_template_with_no_layout + get :index, :format => :js + assert_equal "Hello Firefox", @response.body + end +end + +class FlashResponder < ActionController::Responder + def initialize(controller, resources, options={}) + super + end + + def to_html + controller.flash[:notice] = 'Success' + super + end +end + +class FlashResponderController < ActionController::Base + self.responder = FlashResponder + respond_to :html + + def index + respond_with Object.new do |format| + format.html { render :text => 'HTML' } + end + end +end + +class FlashResponderControllerTest < ActionController::TestCase + tests FlashResponderController + + def test_respond_with_block_executed + get :index + assert_equal 'HTML', @response.body + end + + def test_flash_responder_executed + get :index + assert_equal 'Success', flash[:notice] + end end diff --git a/actionpack/test/controller/new_base/bare_metal_test.rb b/actionpack/test/controller/new_base/bare_metal_test.rb index 3ca29f1bcf..c424dcbd8d 100644 --- a/actionpack/test/controller/new_base/bare_metal_test.rb +++ b/actionpack/test/controller/new_base/bare_metal_test.rb @@ -23,6 +23,12 @@ module BareMetalTest assert_equal "Hello world", string end + + test "response_body value is wrapped in an array when the value is a String" do + controller = BareController.new + controller.index + assert_equal ["Hello world"], controller.response_body + end end class HeadController < ActionController::Metal diff --git a/actionpack/test/controller/new_base/render_file_test.rb b/actionpack/test/controller/new_base/render_file_test.rb index 8b2fdf8f96..a961cbf849 100644 --- a/actionpack/test/controller/new_base/render_file_test.rb +++ b/actionpack/test/controller/new_base/render_file_test.rb @@ -10,7 +10,7 @@ module RenderFile def with_instance_variables @secret = 'in the sauce' - render :file => File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_ivar.erb') + render :file => File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_ivar') end def without_file_key @@ -19,7 +19,7 @@ module RenderFile def without_file_key_with_instance_variable @secret = 'in the sauce' - render File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_ivar.erb') + render File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_ivar') end def relative_path @@ -34,16 +34,16 @@ module RenderFile def pathname @secret = 'in the sauce' - render :file => Pathname.new(File.dirname(__FILE__)).join(*%w[.. .. fixtures test dot.directory render_file_with_ivar.erb]) + render :file => Pathname.new(File.dirname(__FILE__)).join(*%w[.. .. fixtures test dot.directory render_file_with_ivar]) end def with_locals - path = File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_locals.erb') + path = File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_locals') render :file => path, :locals => {:secret => 'in the sauce'} end def without_file_key_with_locals - path = FIXTURES.join('test/render_file_with_locals.erb').to_s + path = FIXTURES.join('test/render_file_with_locals').to_s render path, :locals => {:secret => 'in the sauce'} end end diff --git a/actionpack/test/controller/new_base/render_layout_test.rb b/actionpack/test/controller/new_base/render_layout_test.rb index d3dcb5cad6..4ac40ca405 100644 --- a/actionpack/test/controller/new_base/render_layout_test.rb +++ b/actionpack/test/controller/new_base/render_layout_test.rb @@ -71,7 +71,8 @@ module ControllerLayouts self.view_paths = [ActionView::FixtureResolver.new( "layouts/application.html.erb" => "<html><%= yield %></html>", "controller_layouts/mismatch_format/index.xml.builder" => "xml.instruct!", - "controller_layouts/mismatch_format/implicit.builder" => "xml.instruct!" + "controller_layouts/mismatch_format/implicit.builder" => "xml.instruct!", + "controller_layouts/mismatch_format/explicit.js.erb" => "alert('foo');" )] def explicit @@ -81,7 +82,7 @@ module ControllerLayouts class MismatchFormatTest < Rack::TestCase testing ControllerLayouts::MismatchFormatController - + XML_INSTRUCT = %Q(<?xml version="1.0" encoding="UTF-8"?>\n) test "if XML is selected, an HTML template is not also selected" do @@ -94,10 +95,33 @@ module ControllerLayouts assert_response XML_INSTRUCT end - test "if an HTML template is explicitly provides for a JS template, an error is raised" do - assert_raises ActionView::MissingTemplate do - get :explicit, {}, "action_dispatch.show_exceptions" => false - end + test "a layout for JS is ignored even if explicitly provided for HTML" do + get :explicit, { :format => "js" } + assert_response "alert('foo');" + end + end + + class FalseLayoutMethodController < ::ApplicationController + self.view_paths = [ActionView::FixtureResolver.new( + "controller_layouts/false_layout_method/index.js.erb" => "alert('foo');" + )] + + layout :which_layout? + + def which_layout? + false + end + + def index + end + end + + class FalseLayoutMethodTest < Rack::TestCase + testing ControllerLayouts::FalseLayoutMethodController + + test "access false layout returned by a method/proc" do + get :index, :format => "js" + assert_response "alert('foo');" end end end diff --git a/actionpack/test/controller/new_base/render_partial_test.rb b/actionpack/test/controller/new_base/render_partial_test.rb index 83b0d039ad..b4a25c49c9 100644 --- a/actionpack/test/controller/new_base/render_partial_test.rb +++ b/actionpack/test/controller/new_base/render_partial_test.rb @@ -7,12 +7,12 @@ module RenderPartial self.view_paths = [ActionView::FixtureResolver.new( "render_partial/basic/_basic.html.erb" => "BasicPartial!", "render_partial/basic/basic.html.erb" => "<%= @test_unchanged = 'goodbye' %><%= render :partial => 'basic' %><%= @test_unchanged %>", - "render_partial/basic/with_json.html.erb" => "<%= render 'with_json.json' %>", - "render_partial/basic/_with_json.json.erb" => "<%= render 'final' %>", + "render_partial/basic/with_json.html.erb" => "<%= render :partial => 'with_json', :formats => [:json] %>", + "render_partial/basic/_with_json.json.erb" => "<%= render :partial => 'final', :formats => [:json] %>", "render_partial/basic/_final.json.erb" => "{ final: json }", - "render_partial/basic/overriden.html.erb" => "<%= @test_unchanged = 'goodbye' %><%= render :partial => 'overriden' %><%= @test_unchanged %>", - "render_partial/basic/_overriden.html.erb" => "ParentPartial!", - "render_partial/child/_overriden.html.erb" => "OverridenPartial!" + "render_partial/basic/overriden.html.erb" => "<%= @test_unchanged = 'goodbye' %><%= render :partial => 'overriden' %><%= @test_unchanged %>", + "render_partial/basic/_overriden.html.erb" => "ParentPartial!", + "render_partial/child/_overriden.html.erb" => "OverridenPartial!" )] def html_with_json_inside_json diff --git a/actionpack/test/controller/new_base/render_streaming_test.rb b/actionpack/test/controller/new_base/render_streaming_test.rb index 1a17e24914..61ea68e3f7 100644 --- a/actionpack/test/controller/new_base/render_streaming_test.rb +++ b/actionpack/test/controller/new_base/render_streaming_test.rb @@ -85,7 +85,7 @@ module RenderStreaming test "rendering with template exception logs the exception" do io = StringIO.new - _old, ActionController::Base.logger = ActionController::Base.logger, Logger.new(io) + _old, ActionController::Base.logger = ActionController::Base.logger, ActiveSupport::Logger.new(io) begin get "/render_streaming/basic/template_exception" @@ -111,4 +111,4 @@ module RenderStreaming assert_equal cache, headers["Cache-Control"] end end -end if defined?(Fiber) +end diff --git a/actionpack/test/controller/new_base/render_template_test.rb b/actionpack/test/controller/new_base/render_template_test.rb index 584f2d772c..ade204c387 100644 --- a/actionpack/test/controller/new_base/render_template_test.rb +++ b/actionpack/test/controller/new_base/render_template_test.rb @@ -10,8 +10,8 @@ module RenderTemplate "xml_template.xml.builder" => "xml.html do\n xml.p 'Hello'\nend", "with_raw.html.erb" => "Hello <%=raw '<strong>this is raw</strong>' %>", "with_implicit_raw.html.erb" => "Hello <%== '<strong>this is also raw</strong>' %>", - "test/with_json.html.erb" => "<%= render :template => 'test/with_json.json' %>", - "test/with_json.json.erb" => "<%= render :template => 'test/final' %>", + "test/with_json.html.erb" => "<%= render :template => 'test/with_json', :formats => [:json] %>", + "test/with_json.json.erb" => "<%= render :template => 'test/final', :formats => [:json] %>", "test/final.json.erb" => "{ final: json }", "test/with_error.html.erb" => "<%= idontexist %>" )] @@ -59,6 +59,12 @@ module RenderTemplate def with_error render :template => "test/with_error" end + + private + + def show_detailed_exceptions? + request.local? + end end class TestWithoutLayout < Rack::TestCase @@ -117,7 +123,7 @@ module RenderTemplate assert_response "{ final: json }" end - test "rendering a template with error properly exceprts the code" do + test "rendering a template with error properly excerts the code" do get :with_error assert_status 500 assert_match "undefined local variable or method `idontexist'", response.body diff --git a/actionpack/test/controller/params_wrapper_test.rb b/actionpack/test/controller/params_wrapper_test.rb index 7bef1e8d5d..c4d2614200 100644 --- a/actionpack/test/controller/params_wrapper_test.rb +++ b/actionpack/test/controller/params_wrapper_test.rb @@ -147,6 +147,7 @@ class ParamsWrapperTest < ActionController::TestCase end def test_derived_wrapped_keys_from_matching_model + User.expects(:respond_to?).with(:accessible_attributes).returns(false) User.expects(:respond_to?).with(:attribute_names).returns(true) User.expects(:attribute_names).twice.returns(["username"]) @@ -159,6 +160,7 @@ class ParamsWrapperTest < ActionController::TestCase def test_derived_wrapped_keys_from_specified_model with_default_wrapper_options do + Person.expects(:respond_to?).with(:accessible_attributes).returns(false) Person.expects(:respond_to?).with(:attribute_names).returns(true) Person.expects(:attribute_names).twice.returns(["username"]) @@ -169,8 +171,33 @@ class ParamsWrapperTest < ActionController::TestCase assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'person' => { 'username' => 'sikachu' }}) end end + + def test_accessible_wrapped_keys_from_matching_model + User.expects(:respond_to?).with(:accessible_attributes).returns(true) + User.expects(:accessible_attributes).twice.returns(["username"]) + + with_default_wrapper_options do + @request.env['CONTENT_TYPE'] = 'application/json' + post :parse, { 'username' => 'sikachu', 'title' => 'Developer' } + assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'user' => { 'username' => 'sikachu' }}) + end + end + + def test_accessible_wrapped_keys_from_specified_model + with_default_wrapper_options do + Person.expects(:respond_to?).with(:accessible_attributes).returns(true) + Person.expects(:accessible_attributes).twice.returns(["username"]) + + UsersController.wrap_parameters Person + + @request.env['CONTENT_TYPE'] = 'application/json' + post :parse, { 'username' => 'sikachu', 'title' => 'Developer' } + assert_parameters({ 'username' => 'sikachu', 'title' => 'Developer', 'person' => { 'username' => 'sikachu' }}) + end + end def test_not_wrapping_abstract_model + User.expects(:respond_to?).with(:accessible_attributes).returns(false) User.expects(:respond_to?).with(:attribute_names).returns(true) User.expects(:attribute_names).returns([]) @@ -285,3 +312,38 @@ class AnonymousControllerParamsWrapperTest < ActionController::TestCase end end end + +class IrregularInflectionParamsWrapperTest < ActionController::TestCase + include ParamsWrapperTestHelp + + class ParamswrappernewsItem + def self.attribute_names + ['test_attr'] + end + end + + class ParamswrappernewsController < ActionController::Base + class << self + attr_accessor :last_parameters + end + + def parse + self.class.last_parameters = request.params.except(:controller, :action) + head :ok + end + end + + tests ParamswrappernewsController + + def test_uses_model_attribute_names_with_irregular_inflection + ActiveSupport::Inflector.inflections do |inflect| + inflect.irregular 'paramswrappernews_item', 'paramswrappernews' + end + + with_default_wrapper_options do + @request.env['CONTENT_TYPE'] = 'application/json' + post :parse, { 'username' => 'sikachu', 'test_attr' => 'test_value' } + assert_parameters({ 'username' => 'sikachu', 'test_attr' => 'test_value', 'paramswrappernews_item' => { 'test_attr' => 'test_value' }}) + end + end +end diff --git a/actionpack/test/controller/record_identifier_test.rb b/actionpack/test/controller/record_identifier_test.rb index f3e5ff8a47..eb38b81e85 100644 --- a/actionpack/test/controller/record_identifier_test.rb +++ b/actionpack/test/controller/record_identifier_test.rb @@ -1,7 +1,7 @@ require 'abstract_unit' require 'controller/fake_models' -class RecordIdentifierTest < Test::Unit::TestCase +class RecordIdentifierTest < ActiveSupport::TestCase include ActionController::RecordIdentifier def setup diff --git a/actionpack/test/controller/redirect_test.rb b/actionpack/test/controller/redirect_test.rb index 79041055bd..6dab42d75d 100644 --- a/actionpack/test/controller/redirect_test.rb +++ b/actionpack/test/controller/redirect_test.rb @@ -70,6 +70,10 @@ class RedirectController < ActionController::Base redirect_to "x-test+scheme.complex:redirect" end + def redirect_to_url_with_network_path_reference + redirect_to "//www.rubyonrails.org/" + end + def redirect_to_back redirect_to :back end @@ -99,9 +103,15 @@ class RedirectController < ActionController::Base redirect_to proc { {:action => "hello_world"} } end - def rescue_errors(e) raise e end + def redirect_with_header_break + redirect_to "/lol\r\nwat" + end - def rescue_action(e) raise end + def redirect_with_null_bytes + redirect_to "\000/lol\r\nwat" + end + + def rescue_errors(e) raise e end protected def dashbord_url(id, message) @@ -118,6 +128,18 @@ class RedirectTest < ActionController::TestCase assert_equal "http://test.host/redirect/hello_world", redirect_to_url end + def test_redirect_with_header_break + get :redirect_with_header_break + assert_response :redirect + assert_equal "http://test.host/lolwat", redirect_to_url + end + + def test_redirect_with_null_bytes + get :redirect_with_null_bytes + assert_response :redirect + assert_equal "http://test.host/lolwat", redirect_to_url + end + def test_redirect_with_no_status get :simple_redirect assert_response 302 @@ -216,6 +238,12 @@ class RedirectTest < ActionController::TestCase assert_equal "x-test+scheme.complex:redirect", redirect_to_url end + def test_redirect_to_url_with_network_path_reference + get :redirect_to_url_with_network_path_reference + assert_response :redirect + assert_equal "//www.rubyonrails.org/", redirect_to_url + end + def test_redirect_to_back @request.env["HTTP_REFERER"] = "http://www.example.com/coming/from" get :redirect_to_back diff --git a/actionpack/test/controller/render_json_test.rb b/actionpack/test/controller/render_json_test.rb index fc604a2db3..75fed8e933 100644 --- a/actionpack/test/controller/render_json_test.rb +++ b/actionpack/test/controller/render_json_test.rb @@ -1,5 +1,6 @@ require 'abstract_unit' require 'controller/fake_models' +require 'active_support/logger' require 'pathname' class RenderJsonTest < ActionController::TestCase @@ -69,7 +70,7 @@ class RenderJsonTest < ActionController::TestCase # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get # a more accurate simulation of what happens in "real life". super - @controller.logger = Logger.new(nil) + @controller.logger = ActiveSupport::Logger.new(nil) @request.host = "www.nextangle.com" end diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb index c46755417f..fce13d096c 100644 --- a/actionpack/test/controller/render_test.rb +++ b/actionpack/test/controller/render_test.rb @@ -9,7 +9,7 @@ module Fun end def nested_partial_with_form_builder - render :partial => ActionView::Helpers::FormBuilder.new(:post, nil, view_context, {}, Proc.new {}) + render :partial => ActionView::Helpers::FormBuilder.new(:post, nil, view_context, {}) end end end @@ -25,6 +25,8 @@ end class TestController < ActionController::Base protect_from_forgery + before_filter :set_variable_for_layout + class LabellingFormBuilder < ActionView::Helpers::FormBuilder end @@ -41,7 +43,7 @@ class TestController < ActionController::Base end def hello_world_file - render :file => File.expand_path("../../fixtures/hello.html", __FILE__) + render :file => File.expand_path("../../fixtures/hello", __FILE__), :formats => [:html] end def conditional_hello @@ -50,12 +52,28 @@ class TestController < ActionController::Base end end + def conditional_hello_with_record + record = Struct.new(:updated_at, :cache_key).new(Time.now.utc.beginning_of_day, "foo/123") + + if stale?(record) + render :action => 'hello_world' + end + end + def conditional_hello_with_public_header if stale?(:last_modified => Time.now.utc.beginning_of_day, :etag => [:foo, 123], :public => true) render :action => 'hello_world' end end + def conditional_hello_with_public_header_with_record + record = Struct.new(:updated_at, :cache_key).new(Time.now.utc.beginning_of_day, "foo/123") + + if stale?(record, :public => true) + render :action => 'hello_world' + end + end + def conditional_hello_with_public_header_and_expires_at expires_in 1.minute if stale?(:last_modified => Time.now.utc.beginning_of_day, :etag => [:foo, 123], :public => true) @@ -73,6 +91,16 @@ class TestController < ActionController::Base render :action => 'hello_world' end + def conditional_hello_with_expires_in_with_must_revalidate + expires_in 1.minute, :must_revalidate => true + render :action => 'hello_world' + end + + def conditional_hello_with_expires_in_with_public_and_must_revalidate + expires_in 1.minute, :public => true, :must_revalidate => true + render :action => 'hello_world' + end + def conditional_hello_with_expires_in_with_public_with_more_keys expires_in 1.minute, :public => true, 'max-stale' => 5.hours render :action => 'hello_world' @@ -163,14 +191,14 @@ class TestController < ActionController::Base # :ported: def render_file_with_instance_variables @secret = 'in the sauce' - path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb') + path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar') render :file => path end # :ported: def render_file_as_string_with_instance_variables @secret = 'in the sauce' - path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb')) + path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar')) render path end @@ -187,21 +215,21 @@ class TestController < ActionController::Base def render_file_using_pathname @secret = 'in the sauce' - render :file => Pathname.new(File.dirname(__FILE__)).join('..', 'fixtures', 'test', 'dot.directory', 'render_file_with_ivar.erb') + render :file => Pathname.new(File.dirname(__FILE__)).join('..', 'fixtures', 'test', 'dot.directory', 'render_file_with_ivar') end def render_file_from_template @secret = 'in the sauce' - @path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb')) + @path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar')) end def render_file_with_locals - path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_locals.erb') + path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_locals') render :file => path, :locals => {:secret => 'in the sauce'} end def render_file_as_string_with_locals - path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_locals.erb')) + path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_locals')) render path, :locals => {:secret => 'in the sauce'} end @@ -348,17 +376,14 @@ class TestController < ActionController::Base end def layout_test_with_different_layout - @variable_for_layout = nil render :action => "hello_world", :layout => "standard" end def layout_test_with_different_layout_and_string_action - @variable_for_layout = nil render "hello_world", :layout => "standard" end def layout_test_with_different_layout_and_symbol_action - @variable_for_layout = nil render :hello_world, :layout => "standard" end @@ -367,7 +392,6 @@ class TestController < ActionController::Base end def layout_overriding_layout - @variable_for_layout = nil render :action => "hello_world", :layout => "standard" end @@ -453,17 +477,13 @@ class TestController < ActionController::Base render :action => "potential_conflicts" end - # :deprecated: - # Tests being able to pick a .builder template over a .erb - # For instance, being able to have hello.xml.builder and hello.xml.erb - # and select one via "hello.builder" or "hello.erb" def hello_world_from_rxml_using_action - render :action => "hello_world_from_rxml.builder" + render :action => "hello_world_from_rxml", :handlers => [:builder] end # :deprecated: def hello_world_from_rxml_using_template - render :template => "test/hello_world_from_rxml.builder" + render :template => "test/hello_world_from_rxml", :handlers => [:builder] end def action_talk_to_layout @@ -525,20 +545,41 @@ class TestController < ActionController::Base render :action => "using_layout_around_block", :layout => "layouts/block_with_layout" end - def partial_dot_html - render :partial => 'partial.html.erb' + def partial_formats_html + render :partial => 'partial', :formats => [:html] end def partial render :partial => 'partial' end + def partial_html_erb + render :partial => 'partial_html_erb' + end + def render_to_string_with_partial @partial_only = render_to_string :partial => "partial_only" @partial_with_locals = render_to_string :partial => "customer", :locals => { :customer => Customer.new("david") } render :template => "test/hello_world" end + def render_to_string_with_template_and_html_partial + @text = render_to_string :template => "test/with_partial", :formats => [:text] + @html = render_to_string :template => "test/with_partial", :formats => [:html] + render :template => "test/with_html_partial" + end + + def render_to_string_and_render_with_different_formats + @html = render_to_string :template => "test/with_partial", :formats => [:html] + render :template => "test/with_partial", :formats => [:text] + end + + def render_template_within_a_template_with_other_format + render :template => "test/with_xml_template", + :formats => [:html], + :layout => "with_html_partial" + end + def partial_with_counter render :partial => "counter", :locals => { :counter_counter => 5 } end @@ -548,11 +589,11 @@ class TestController < ActionController::Base end def partial_with_form_builder - render :partial => ActionView::Helpers::FormBuilder.new(:post, nil, view_context, {}, Proc.new {}) + render :partial => ActionView::Helpers::FormBuilder.new(:post, nil, view_context, {}) end def partial_with_form_builder_subclass - render :partial => LabellingFormBuilder.new(:post, nil, view_context, {}, Proc.new {}) + render :partial => LabellingFormBuilder.new(:post, nil, view_context, {}) end def partial_collection @@ -639,10 +680,6 @@ class TestController < ActionController::Base render :action => "calling_partial_with_layout", :layout => "layouts/partial_with_layout" end - def rescue_action(e) - raise - end - before_filter :only => :render_with_filters do request.format = :xml end @@ -654,8 +691,11 @@ class TestController < ActionController::Base private + def set_variable_for_layout + @variable_for_layout = nil + end + def determine_layout - @variable_for_layout ||= nil case action_name when "hello_world", "layout_test", "rendering_without_layout", "rendering_nothing_on_layout", "render_text_hello_world", @@ -683,7 +723,8 @@ class RenderTest < ActionController::TestCase # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get # a more accurate simulation of what happens in "real life". super - @controller.logger = Logger.new(nil) + @controller.logger = ActiveSupport::Logger.new(nil) + ActionView::Base.logger = ActiveSupport::Logger.new(nil) @request.host = "www.nextangle.com" end @@ -878,12 +919,12 @@ class RenderTest < ActionController::TestCase # :ported: def test_attempt_to_access_object_method - assert_raise(ActionController::UnknownAction, "No action responded to [clone]") { get :clone } + assert_raise(AbstractController::ActionNotFound, "No action responded to [clone]") { get :clone } end # :ported: def test_private_methods - assert_raise(ActionController::UnknownAction, "No action responded to [determine_layout]") { get :determine_layout } + assert_raise(AbstractController::ActionNotFound, "No action responded to [determine_layout]") { get :determine_layout } end # :ported: @@ -894,7 +935,7 @@ class RenderTest < ActionController::TestCase def test_access_to_logger_in_view get :accessing_logger_in_template - assert_equal "Logger", @response.body + assert_equal "ActiveSupport::Logger", @response.body end # :ported: @@ -981,6 +1022,7 @@ class RenderTest < ActionController::TestCase def test_accessing_local_assigns_in_inline_template get :accessing_local_assigns_in_inline_template, :local_name => "Local David" assert_equal "Goodbye, Local David", @response.body + assert_equal "text/html", @response.content_type end def test_should_implicitly_render_html_template_from_xhr_request @@ -1083,15 +1125,15 @@ class RenderTest < ActionController::TestCase # :ported: def test_double_render - assert_raise(ActionController::DoubleRenderError) { get :double_render } + assert_raise(AbstractController::DoubleRenderError) { get :double_render } end def test_double_redirect - assert_raise(ActionController::DoubleRenderError) { get :double_redirect } + assert_raise(AbstractController::DoubleRenderError) { get :double_redirect } end def test_render_and_redirect - assert_raise(ActionController::DoubleRenderError) { get :render_and_redirect } + assert_raise(AbstractController::DoubleRenderError) { get :render_and_redirect } end # specify the one exception to double render rule - render_to_string followed by render @@ -1226,22 +1268,57 @@ class RenderTest < ActionController::TestCase def test_partial_only get :partial_only assert_equal "only partial", @response.body + assert_equal "text/html", @response.content_type end def test_should_render_html_formatted_partial get :partial - assert_equal 'partial html', @response.body + assert_equal "partial html", @response.body + assert_equal "text/html", @response.content_type + end + + def test_render_html_formatted_partial_even_with_other_mime_time_in_accept + @request.accept = "text/javascript, text/html" + + get :partial_html_erb + + assert_equal "partial.html.erb", @response.body.strip + assert_equal "text/html", @response.content_type end - def test_should_render_html_partial_with_dot - get :partial_dot_html - assert_equal 'partial html', @response.body + def test_should_render_html_partial_with_formats + get :partial_formats_html + assert_equal "partial html", @response.body + assert_equal "text/html", @response.content_type end def test_render_to_string_partial get :render_to_string_with_partial assert_equal "only partial", assigns(:partial_only) assert_equal "Hello: david", assigns(:partial_with_locals) + assert_equal "text/html", @response.content_type + end + + def test_render_to_string_with_template_and_html_partial + get :render_to_string_with_template_and_html_partial + assert_equal "**only partial**\n", assigns(:text) + assert_equal "<strong>only partial</strong>\n", assigns(:html) + assert_equal "<strong>only html partial</strong>\n", @response.body + assert_equal "text/html", @response.content_type + end + + def test_render_to_string_and_render_with_different_formats + get :render_to_string_and_render_with_different_formats + assert_equal "<strong>only partial</strong>\n", assigns(:html) + assert_equal "**only partial**\n", @response.body + assert_equal "text/plain", @response.content_type + end + + def test_render_template_within_a_template_with_other_format + get :render_template_within_a_template_with_other_format + expected = "only html partial<p>This is grand!</p>" + assert_equal expected, @response.body.strip + assert_equal "text/html", @response.content_type end def test_partial_with_counter @@ -1389,6 +1466,16 @@ class ExpiresInRenderTest < ActionController::TestCase assert_equal "max-age=60, public", @response.headers["Cache-Control"] end + def test_expires_in_header_with_must_revalidate + get :conditional_hello_with_expires_in_with_must_revalidate + assert_equal "max-age=60, private, must-revalidate", @response.headers["Cache-Control"] + end + + def test_expires_in_header_with_public_and_must_revalidate + get :conditional_hello_with_expires_in_with_public_and_must_revalidate + assert_equal "max-age=60, public, must-revalidate", @response.headers["Cache-Control"] + end + def test_expires_in_header_with_additional_headers get :conditional_hello_with_expires_in_with_public_with_more_keys assert_equal "max-age=60, public, max-stale=18000", @response.headers["Cache-Control"] @@ -1403,6 +1490,13 @@ class ExpiresInRenderTest < ActionController::TestCase get :conditional_hello_with_expires_now assert_equal "no-cache", @response.headers["Cache-Control"] end + + def test_date_header_when_expires_in + time = Time.mktime(2011,10,30) + Time.stubs(:now).returns(time) + get :conditional_hello_with_expires_in + assert_equal Time.now.httpdate, @response.headers["Date"] + end end class LastModifiedRenderTest < ActionController::TestCase @@ -1442,6 +1536,36 @@ class LastModifiedRenderTest < ActionController::TestCase assert_equal @last_modified, @response.headers['Last-Modified'] end + + def test_responds_with_last_modified_with_record + get :conditional_hello_with_record + assert_equal @last_modified, @response.headers['Last-Modified'] + end + + def test_request_not_modified_with_record + @request.if_modified_since = @last_modified + get :conditional_hello_with_record + assert_equal 304, @response.status.to_i + assert_blank @response.body + assert_equal @last_modified, @response.headers['Last-Modified'] + end + + def test_request_not_modified_but_etag_differs_with_record + @request.if_modified_since = @last_modified + @request.if_none_match = "234" + get :conditional_hello_with_record + assert_response :success + end + + def test_request_modified_with_record + @request.if_modified_since = 'Thu, 16 Jul 2008 00:00:00 GMT' + get :conditional_hello_with_record + assert_equal 200, @response.status.to_i + assert_present @response.body + assert_equal @last_modified, @response.headers['Last-Modified'] + end + + def test_request_with_bang_gets_last_modified get :conditional_hello_with_bangs assert_equal @last_modified, @response.headers['Last-Modified'] diff --git a/actionpack/test/controller/render_xml_test.rb b/actionpack/test/controller/render_xml_test.rb index ec4dc848ff..8b4f2f5349 100644 --- a/actionpack/test/controller/render_xml_test.rb +++ b/actionpack/test/controller/render_xml_test.rb @@ -48,7 +48,7 @@ class RenderXmlTest < ActionController::TestCase # enable a logger so that (e.g.) the benchmarking stuff runs, so we can get # a more accurate simulation of what happens in "real life". super - @controller.logger = Logger.new(nil) + @controller.logger = ActiveSupport::Logger.new(nil) @request.host = "www.nextangle.com" end diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb index fd5a41a0bb..066cd523be 100644 --- a/actionpack/test/controller/request_forgery_protection_test.rb +++ b/actionpack/test/controller/request_forgery_protection_test.rb @@ -1,6 +1,5 @@ require 'abstract_unit' require 'digest/sha1' -require 'active_support/core_ext/string/strip' require "active_support/log_subscriber/test_helper" # common controller actions @@ -37,6 +36,22 @@ module RequestForgeryProtectionActions render :inline => "<%= form_for(:some_resource, :authenticity_token => false ) {} %>" end + def form_for_remote + render :inline => "<%= form_for(:some_resource, :remote => true ) {} %>" + end + + def form_for_remote_with_token + render :inline => "<%= form_for(:some_resource, :remote => true, :authenticity_token => true ) {} %>" + end + + def form_for_with_token + render :inline => "<%= form_for(:some_resource, :authenticity_token => true ) {} %>" + end + + def form_for_remote_with_external_token + render :inline => "<%= form_for(:some_resource, :remote => true, :authenticity_token => 'external_token') {} %>" + end + def rescue_action(e) raise e end end @@ -46,7 +61,7 @@ class RequestForgeryProtectionController < ActionController::Base protect_from_forgery :only => %w(index meta) end -class RequestForgeryProtectionControllerUsingOldBehaviour < ActionController::Base +class RequestForgeryProtectionControllerUsingException < ActionController::Base include RequestForgeryProtectionActions protect_from_forgery :only => %w(index meta) @@ -74,9 +89,7 @@ class CustomAuthenticityParamController < RequestForgeryProtectionController end end - # common test methods - module RequestForgeryProtectionTests def setup @token = "cf50faa3fe97702ca1ae" @@ -103,6 +116,60 @@ module RequestForgeryProtectionTests assert_select 'form>div>input[name=?][value=?]', 'custom_authenticity_token', @token end + def test_should_render_form_without_token_tag_if_remote + assert_not_blocked do + get :form_for_remote + end + assert_no_match(/authenticity_token/, response.body) + end + + def test_should_render_form_with_token_tag_if_remote_and_embedding_token_is_on + original = ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms + begin + ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = true + assert_not_blocked do + get :form_for_remote + end + assert_match(/authenticity_token/, response.body) + ensure + ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = original + end + end + + def test_should_render_form_with_token_tag_if_remote_and_external_authenticity_token_requested_and_embedding_is_on + original = ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms + begin + ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = true + assert_not_blocked do + get :form_for_remote_with_external_token + end + assert_select 'form>div>input[name=?][value=?]', 'custom_authenticity_token', 'external_token' + ensure + ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = original + end + end + + def test_should_render_form_with_token_tag_if_remote_and_external_authenticity_token_requested + assert_not_blocked do + get :form_for_remote_with_external_token + end + assert_select 'form>div>input[name=?][value=?]', 'custom_authenticity_token', 'external_token' + end + + def test_should_render_form_with_token_tag_if_remote_and_authenticity_token_requested + assert_not_blocked do + get :form_for_remote_with_token + end + assert_select 'form>div>input[name=?][value=?]', 'custom_authenticity_token', @token + end + + def test_should_render_form_with_token_tag_with_authenticity_token_requested + assert_not_blocked do + get :form_for_with_token + end + assert_select 'form>div>input[name=?][value=?]', 'custom_authenticity_token', @token + end + def test_should_allow_get assert_not_blocked { get :index } end @@ -119,6 +186,10 @@ module RequestForgeryProtectionTests assert_blocked { post :index, :format=>'xml' } end + def test_should_not_allow_patch_without_token + assert_blocked { patch :index } + end + def test_should_not_allow_put_without_token assert_blocked { put :index } end @@ -135,6 +206,10 @@ module RequestForgeryProtectionTests assert_not_blocked { post :index, :custom_authenticity_token => @token } end + def test_should_allow_patch_with_token + assert_not_blocked { patch :index, :custom_authenticity_token => @token } + end + def test_should_allow_put_with_token assert_not_blocked { put :index, :custom_authenticity_token => @token } end @@ -153,6 +228,11 @@ module RequestForgeryProtectionTests assert_not_blocked { delete :index } end + def test_should_allow_patch_with_token_in_header + @request.env['HTTP_X_CSRF_TOKEN'] = @token + assert_not_blocked { patch :index } + end + def test_should_allow_put_with_token_in_header @request.env['HTTP_X_CSRF_TOKEN'] = @token assert_not_blocked { put :index } @@ -207,7 +287,7 @@ class RequestForgeryProtectionControllerTest < ActionController::TestCase end end -class RequestForgeryProtectionControllerUsingOldBehaviourTest < ActionController::TestCase +class RequestForgeryProtectionControllerUsingExceptionTest < ActionController::TestCase include RequestForgeryProtectionTests def assert_blocked assert_raises(ActionController::InvalidAuthenticityToken) do @@ -237,7 +317,7 @@ class FreeCookieControllerTest < ActionController::TestCase end def test_should_allow_all_methods_without_token - [:post, :put, :delete].each do |method| + [:post, :patch, :put, :delete].each do |method| assert_nothing_raised { send(method, :index)} end end @@ -248,10 +328,6 @@ class FreeCookieControllerTest < ActionController::TestCase end end - - - - class CustomAuthenticityParamControllerTest < ActionController::TestCase def setup ActionController::Base.request_forgery_protection_token = :custom_token_name diff --git a/actionpack/test/controller/rescue_test.rb b/actionpack/test/controller/rescue_test.rb index c445285538..9c51db135b 100644 --- a/actionpack/test/controller/rescue_test.rb +++ b/actionpack/test/controller/rescue_test.rb @@ -137,11 +137,11 @@ class RescueController < ActionController::Base end def io_error_in_view - raise ActionView::TemplateError.new(nil, {}, IOError.new('this is io error')) + raise ActionView::TemplateError.new(nil, IOError.new('this is io error')) end def zero_division_error_in_view - raise ActionView::TemplateError.new(nil, {}, ZeroDivisionError.new('this is zero division error')) + raise ActionView::TemplateError.new(nil, ZeroDivisionError.new('this is zero division error')) end protected @@ -338,23 +338,8 @@ class RescueTest < ActionDispatch::IntegrationTest end end - test 'rescue routing exceptions' do - raiser = proc { |env| raise ActionController::RoutingError, "Did not handle the request" } - @app = ActionDispatch::Rescue.new(raiser) do - rescue_from ActionController::RoutingError, lambda { |env| [200, {"Content-Type" => "text/html"}, ["Gotcha!"]] } - end - - get '/b00m' - assert_equal "Gotcha!", response.body - end - - test 'unrescued exception' do - raiser = proc { |env| raise ActionController::RoutingError, "Did not handle the request" } - @app = ActionDispatch::Rescue.new(raiser) - assert_raise(ActionController::RoutingError) { get '/b00m' } - end - private + def with_test_routing with_routing do |set| set.draw do diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb index 6b8a8f6161..3c0a5d36ca 100644 --- a/actionpack/test/controller/resources_test.rb +++ b/actionpack/test/controller/resources_test.rb @@ -6,7 +6,6 @@ require 'active_support/core_ext/object/inclusion' class ResourcesController < ActionController::Base def index() render :nothing => true end alias_method :show, :index - def rescue_action(e) raise e end end class ThreadsController < ResourcesController; end @@ -159,7 +158,7 @@ class ResourcesTest < ActionController::TestCase end def test_with_collection_actions - actions = { 'a' => :get, 'b' => :put, 'c' => :post, 'd' => :delete } + actions = { 'a' => :get, 'b' => :put, 'c' => :post, 'd' => :delete, 'e' => :patch } with_routing do |set| set.draw do @@ -168,6 +167,7 @@ class ResourcesTest < ActionController::TestCase put :b, :on => :collection post :c, :on => :collection delete :d, :on => :collection + patch :e, :on => :collection end end @@ -186,7 +186,7 @@ class ResourcesTest < ActionController::TestCase end def test_with_collection_actions_and_name_prefix - actions = { 'a' => :get, 'b' => :put, 'c' => :post, 'd' => :delete } + actions = { 'a' => :get, 'b' => :put, 'c' => :post, 'd' => :delete, 'e' => :patch } with_routing do |set| set.draw do @@ -196,6 +196,7 @@ class ResourcesTest < ActionController::TestCase put :b, :on => :collection post :c, :on => :collection delete :d, :on => :collection + patch :e, :on => :collection end end end @@ -242,7 +243,7 @@ class ResourcesTest < ActionController::TestCase end def test_with_collection_action_and_name_prefix_and_formatted - actions = { 'a' => :get, 'b' => :put, 'c' => :post, 'd' => :delete } + actions = { 'a' => :get, 'b' => :put, 'c' => :post, 'd' => :delete, 'e' => :patch } with_routing do |set| set.draw do @@ -252,6 +253,7 @@ class ResourcesTest < ActionController::TestCase put :b, :on => :collection post :c, :on => :collection delete :d, :on => :collection + patch :e, :on => :collection end end end @@ -271,7 +273,7 @@ class ResourcesTest < ActionController::TestCase end def test_with_member_action - [:put, :post].each do |method| + [:patch, :put, :post].each do |method| with_restful_routing :messages, :member => { :mark => method } do mark_options = {:action => 'mark', :id => '1'} mark_path = "/messages/1/mark" @@ -295,7 +297,7 @@ class ResourcesTest < ActionController::TestCase end def test_member_when_override_paths_for_default_restful_actions_with - [:put, :post].each do |method| + [:patch, :put, :post].each do |method| with_restful_routing :messages, :member => { :mark => method }, :path_names => {:new => 'nuevo'} do mark_options = {:action => 'mark', :id => '1', :controller => "messages"} mark_path = "/messages/1/mark" @@ -312,7 +314,7 @@ class ResourcesTest < ActionController::TestCase end def test_with_two_member_actions_with_same_method - [:put, :post].each do |method| + [:patch, :put, :post].each do |method| with_routing do |set| set.draw do resources :messages do @@ -565,7 +567,7 @@ class ResourcesTest < ActionController::TestCase end def test_singleton_resource_with_member_action - [:put, :post].each do |method| + [:patch, :put, :post].each do |method| with_routing do |set| set.draw do resource :account do @@ -587,7 +589,7 @@ class ResourcesTest < ActionController::TestCase end def test_singleton_resource_with_two_member_actions_with_same_method - [:put, :post].each do |method| + [:patch, :put, :post].each do |method| with_routing do |set| set.draw do resource :account do @@ -652,13 +654,17 @@ class ResourcesTest < ActionController::TestCase end end - def test_should_not_allow_delete_or_put_on_collection_path + def test_should_not_allow_delete_or_patch_or_put_on_collection_path controller_name = :messages with_restful_routing controller_name do options = { :controller => controller_name.to_s } collection_path = "/#{controller_name}" assert_raise(ActionController::RoutingError) do + assert_recognizes(options.merge(:action => 'update'), :path => collection_path, :method => :patch) + end + + assert_raise(ActionController::RoutingError) do assert_recognizes(options.merge(:action => 'update'), :path => collection_path, :method => :put) end diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb index 5bf68decca..272a7da8c5 100644 --- a/actionpack/test/controller/routing_test.rb +++ b/actionpack/test/controller/routing_test.rb @@ -6,19 +6,12 @@ require 'active_support/core_ext/object/with_options' class MilestonesController < ActionController::Base def index() head :ok end alias_method :show, :index - def rescue_action(e) raise e end end ROUTING = ActionDispatch::Routing -module RoutingTestHelpers - def url_for(set, options, recall = nil) - set.send(:url_for, options.merge(:only_path => true, :_path_segments => recall)) - end -end - # See RFC 3986, section 3.3 for allowed path characters. -class UriReservedCharactersRoutingTest < Test::Unit::TestCase +class UriReservedCharactersRoutingTest < ActiveSupport::TestCase include RoutingTestHelpers def setup @@ -66,11 +59,11 @@ end class MockController def self.build(helpers) Class.new do - def url_for(options) + def url_options + options = super options[:protocol] ||= "http" options[:host] ||= "test.host" - - super(options) + options end include helpers @@ -78,17 +71,197 @@ class MockController end end -class LegacyRouteSetTests < Test::Unit::TestCase +class LegacyRouteSetTests < ActiveSupport::TestCase include RoutingTestHelpers + include ActionDispatch::RoutingVerbs attr_reader :rs + alias :routes :rs def setup - @rs = ::ActionDispatch::Routing::RouteSet.new + @rs = ::ActionDispatch::Routing::RouteSet.new + @response = nil end - def teardown - @rs.clear! + def test_symbols_with_dashes + rs.draw do + match '/:artist/:song-omg', :to => lambda { |env| + resp = JSON.dump env[ActionDispatch::Routing::RouteSet::PARAMETERS_KEY] + [200, {}, [resp]] + } + end + + hash = JSON.load get(URI('http://example.org/journey/faithfully-omg')) + assert_equal({"artist"=>"journey", "song"=>"faithfully"}, hash) + end + + def test_id_with_dash + rs.draw do + match '/journey/:id', :to => lambda { |env| + resp = JSON.dump env[ActionDispatch::Routing::RouteSet::PARAMETERS_KEY] + [200, {}, [resp]] + } + end + + hash = JSON.load get(URI('http://example.org/journey/faithfully-omg')) + assert_equal({"id"=>"faithfully-omg"}, hash) + end + + def test_dash_with_custom_regexp + rs.draw do + match '/:artist/:song-omg', :constraints => { :song => /\d+/ }, :to => lambda { |env| + resp = JSON.dump env[ActionDispatch::Routing::RouteSet::PARAMETERS_KEY] + [200, {}, [resp]] + } + end + + hash = JSON.load get(URI('http://example.org/journey/123-omg')) + assert_equal({"artist"=>"journey", "song"=>"123"}, hash) + assert_equal 'Not Found', get(URI('http://example.org/journey/faithfully-omg')) + end + + def test_pre_dash + rs.draw do + match '/:artist/omg-:song', :to => lambda { |env| + resp = JSON.dump env[ActionDispatch::Routing::RouteSet::PARAMETERS_KEY] + [200, {}, [resp]] + } + end + + hash = JSON.load get(URI('http://example.org/journey/omg-faithfully')) + assert_equal({"artist"=>"journey", "song"=>"faithfully"}, hash) + end + + def test_pre_dash_with_custom_regexp + rs.draw do + match '/:artist/omg-:song', :constraints => { :song => /\d+/ }, :to => lambda { |env| + resp = JSON.dump env[ActionDispatch::Routing::RouteSet::PARAMETERS_KEY] + [200, {}, [resp]] + } + end + + hash = JSON.load get(URI('http://example.org/journey/omg-123')) + assert_equal({"artist"=>"journey", "song"=>"123"}, hash) + assert_equal 'Not Found', get(URI('http://example.org/journey/omg-faithfully')) + end + + def test_star_paths_are_greedy + rs.draw do + match "/*path", :to => lambda { |env| + x = env["action_dispatch.request.path_parameters"][:path] + [200, {}, [x]] + }, :format => false + end + + u = URI('http://example.org/foo/bar.html') + assert_equal u.path.sub(/^\//, ''), get(u) + end + + def test_star_paths_are_greedy_but_not_too_much + rs.draw do + match "/*path", :to => lambda { |env| + x = JSON.dump env["action_dispatch.request.path_parameters"] + [200, {}, [x]] + } + end + + expected = { "path" => "foo/bar", "format" => "html" } + u = URI('http://example.org/foo/bar.html') + assert_equal expected, JSON.parse(get(u)) + end + + def test_optional_star_paths_are_greedy + rs.draw do + match "/(*filters)", :to => lambda { |env| + x = env["action_dispatch.request.path_parameters"][:filters] + [200, {}, [x]] + }, :format => false + end + + u = URI('http://example.org/ne_27.065938,-80.6092/sw_25.489856,-82.542794') + assert_equal u.path.sub(/^\//, ''), get(u) + end + + def test_optional_star_paths_are_greedy_but_not_too_much + rs.draw do + match "/(*filters)", :to => lambda { |env| + x = JSON.dump env["action_dispatch.request.path_parameters"] + [200, {}, [x]] + } + end + + expected = { "filters" => "ne_27.065938,-80.6092/sw_25.489856,-82", + "format" => "542794" } + u = URI('http://example.org/ne_27.065938,-80.6092/sw_25.489856,-82.542794') + assert_equal expected, JSON.parse(get(u)) + end + + def test_regexp_precidence + @rs.draw do + match '/whois/:domain', :constraints => { + :domain => /\w+\.[\w\.]+/ }, + :to => lambda { |env| [200, {}, %w{regexp}] } + + match '/whois/:id', :to => lambda { |env| [200, {}, %w{id}] } + end + + assert_equal 'regexp', get(URI('http://example.org/whois/example.org')) + assert_equal 'id', get(URI('http://example.org/whois/123')) + end + + def test_class_and_lambda_constraints + subdomain = Class.new { + def matches? request + request.subdomain.present? and request.subdomain != 'clients' + end + } + + @rs.draw do + match '/', :constraints => subdomain.new, + :to => lambda { |env| [200, {}, %w{default}] } + match '/', :constraints => { :subdomain => 'clients' }, + :to => lambda { |env| [200, {}, %w{clients}] } + end + + assert_equal 'default', get(URI('http://www.example.org/')) + assert_equal 'clients', get(URI('http://clients.example.org/')) + end + + def test_lambda_constraints + @rs.draw do + match '/', :constraints => lambda { |req| + req.subdomain.present? and req.subdomain != "clients" }, + :to => lambda { |env| [200, {}, %w{default}] } + + match '/', :constraints => lambda { |req| + req.subdomain.present? && req.subdomain == "clients" }, + :to => lambda { |env| [200, {}, %w{clients}] } + end + + assert_equal 'default', get(URI('http://www.example.org/')) + assert_equal 'clients', get(URI('http://clients.example.org/')) + end + + def test_empty_string_match + rs.draw do + get '/:username', :constraints => { :username => /[^\/]+/ }, + :to => lambda { |e| [200, {}, ['foo']] } + end + assert_equal 'Not Found', get(URI('http://example.org/')) + assert_equal 'foo', get(URI('http://example.org/hello')) + end + + def test_non_greedy_glob_regexp + params = nil + rs.draw do + get '/posts/:id(/*filters)', :constraints => { :filters => /.+?/ }, + :to => lambda { |e| + params = e["action_dispatch.request.path_parameters"] + [200, {}, ['foo']] + } + end + assert_equal 'foo', get(URI('http://example.org/posts/1/foo.js')) + assert_equal({:id=>"1", :filters=>"foo", :format=>"js"}, params) end def test_draw_with_block_arity_one_raises @@ -120,36 +293,6 @@ class LegacyRouteSetTests < Test::Unit::TestCase test_default_setup end - def test_time_recognition - # We create many routes to make situation more realistic - @rs = ::ActionDispatch::Routing::RouteSet.new - @rs.draw { - root :to => "search#new", :as => "frontpage" - resources :videos do - resources :comments - resource :file, :controller => 'video_file' - resource :share, :controller => 'video_shares' - resource :abuse, :controller => 'video_abuses' - end - resources :abuses, :controller => 'video_abuses' - resources :video_uploads - resources :video_visits - - resources :users do - resource :settings - resources :videos - end - resources :channels do - resources :videos, :controller => 'channel_videos' - end - resource :session - resource :lost_password - match 'search' => 'search#index', :as => 'search' - resources :pages - match ':controller/:action/:id' - } - end - def test_route_with_colon_first rs.draw do match '/:controller/:action/:id', :action => 'index', :id => nil @@ -294,6 +437,15 @@ class LegacyRouteSetTests < Test::Unit::TestCase assert_equal("/", routes.send(:root_path)) end + def test_named_route_root_without_hash + rs.draw do + root "hello#index" + end + routes = setup_for_named_route + assert_equal("http://test.host/", routes.send(:root_url)) + assert_equal("/", routes.send(:root_path)) + end + def test_named_route_with_regexps rs.draw do match 'page/:year/:month/:day/:title' => 'page#show', :as => 'article', @@ -413,7 +565,7 @@ class LegacyRouteSetTests < Test::Unit::TestCase assert_equal({ :controller => "content", :action => 'show_page', :id => 'foo' }, rs.recognize_path("/page/foo")) token = "\321\202\320\265\320\272\321\201\321\202" # 'text' in Russian - token.force_encoding(Encoding::BINARY) if token.respond_to?(:force_encoding) + token.force_encoding(Encoding::BINARY) escaped_token = CGI::escape(token) assert_equal '/page/' + escaped_token, url_for(rs, { :controller => 'content', :action => 'show_page', :id => token }) @@ -530,11 +682,12 @@ class LegacyRouteSetTests < Test::Unit::TestCase match '/match' => 'books#get', :via => :get match '/match' => 'books#post', :via => :post match '/match' => 'books#put', :via => :put + match '/match' => 'books#patch', :via => :patch match '/match' => 'books#delete', :via => :delete end end - %w(GET POST PUT DELETE).each do |request_method| + %w(GET PATCH POST PUT DELETE).each do |request_method| define_method("test_request_method_recognized_with_#{request_method}") do setup_request_method_routes_for(request_method) params = rs.recognize_path("/match", :method => request_method) @@ -719,12 +872,12 @@ class RouteSetTest < ActiveSupport::TestCase assert_equal set.routes.first, set.named_routes[:hello] end - def test_later_named_routes_take_precedence + def test_earlier_named_routes_take_precedence set.draw do match '/hello/world' => 'a#b', :as => 'hello' match '/hello' => 'a#b', :as => 'hello' end - assert_equal set.routes.last, set.named_routes[:hello] + assert_equal set.routes.first, set.named_routes[:hello] end def setup_named_route_test @@ -917,6 +1070,7 @@ class RouteSetTest < ActiveSupport::TestCase post "/people" => "people#create" get "/people/:id" => "people#show", :as => "person" put "/people/:id" => "people#update" + patch "/people/:id" => "people#update" delete "/people/:id" => "people#destroy" end @@ -929,6 +1083,9 @@ class RouteSetTest < ActiveSupport::TestCase params = set.recognize_path("/people/5", :method => :put) assert_equal("update", params[:action]) + params = set.recognize_path("/people/5", :method => :patch) + assert_equal("update", params[:action]) + assert_raise(ActionController::UnknownHttpMethod) { set.recognize_path("/people", :method => :bacon) } @@ -941,6 +1098,10 @@ class RouteSetTest < ActiveSupport::TestCase assert_equal("update", params[:action]) assert_equal("5", params[:id]) + params = set.recognize_path("/people/5", :method => :patch) + assert_equal("update", params[:action]) + assert_equal("5", params[:id]) + params = set.recognize_path("/people/5", :method => :delete) assert_equal("destroy", params[:action]) assert_equal("5", params[:id]) @@ -994,6 +1155,7 @@ class RouteSetTest < ActiveSupport::TestCase set.draw do get "people/:id" => "people#show", :as => "person" put "people/:id" => "people#update" + patch "people/:id" => "people#update" get "people/:id(.:format)" => "people#show" end @@ -1004,6 +1166,9 @@ class RouteSetTest < ActiveSupport::TestCase params = set.recognize_path("/people/5", :method => :put) assert_equal("update", params[:action]) + params = set.recognize_path("/people/5", :method => :patch) + assert_equal("update", params[:action]) + params = set.recognize_path("/people/5.png", :method => :get) assert_equal("show", params[:action]) assert_equal("5", params[:id]) @@ -1258,7 +1423,20 @@ class RouteSetTest < ActiveSupport::TestCase end end end - + + def test_route_with_subdomain_and_constraints_must_receive_params + name_param = nil + set.draw do + match 'page/:name' => 'pages#show', :constraints => lambda {|request| + name_param = request.params[:name] + return true + } + end + assert_equal({:controller => 'pages', :action => 'show', :name => 'mypage'}, + set.recognize_path('http://subdomain.example.org/page/mypage')) + assert_equal(name_param, 'mypage') + end + def test_route_requirement_recognize_with_ignore_case set.draw do match 'page/:name' => 'pages#show', diff --git a/actionpack/test/controller/runner_test.rb b/actionpack/test/controller/runner_test.rb index 24c220dcd5..3e9383abb2 100644 --- a/actionpack/test/controller/runner_test.rb +++ b/actionpack/test/controller/runner_test.rb @@ -2,7 +2,7 @@ require 'abstract_unit' require 'action_dispatch/testing/integration' module ActionDispatch - class RunnerTest < Test::Unit::TestCase + class RunnerTest < ActiveSupport::TestCase class MyRunner include Integration::Runner diff --git a/actionpack/test/controller/selector_test.rb b/actionpack/test/controller/selector_test.rb index 8ce9e43402..5e302da212 100644 --- a/actionpack/test/controller/selector_test.rb +++ b/actionpack/test/controller/selector_test.rb @@ -7,7 +7,7 @@ require 'abstract_unit' require 'controller/fake_controllers' require 'action_controller/vendor/html-scanner' -class SelectorTest < Test::Unit::TestCase +class SelectorTest < ActiveSupport::TestCase # # Basic selector: element, id, class, attributes. # diff --git a/actionpack/test/controller/send_file_test.rb b/actionpack/test/controller/send_file_test.rb index 8f885ff28e..3af17f495c 100644 --- a/actionpack/test/controller/send_file_test.rb +++ b/actionpack/test/controller/send_file_test.rb @@ -23,10 +23,6 @@ class SendFileController < ActionController::Base def data send_data(file_data, options) end - - def multibyte_text_data - send_data("Кирилица\n祝您好運.", options) - end end class SendFileTest < ActionController::TestCase @@ -61,7 +57,7 @@ class SendFileTest < ActionController::TestCase require 'stringio' output = StringIO.new output.binmode - output.string.force_encoding(file_data.encoding) if output.string.respond_to?(:force_encoding) + output.string.force_encoding(file_data.encoding) assert_nothing_raised { response.body_parts.each { |part| output << part.to_s } } assert_equal file_data, output.string end diff --git a/actionpack/test/controller/show_exceptions_test.rb b/actionpack/test/controller/show_exceptions_test.rb new file mode 100644 index 0000000000..13ab19ed8f --- /dev/null +++ b/actionpack/test/controller/show_exceptions_test.rb @@ -0,0 +1,71 @@ +require 'abstract_unit' + +module ShowExceptions + class ShowExceptionsController < ActionController::Base + use ActionDispatch::ShowExceptions, ActionDispatch::PublicExceptions.new("#{FIXTURE_LOAD_PATH}/public") + use ActionDispatch::DebugExceptions + + before_filter :only => :another_boom do + request.env["action_dispatch.show_detailed_exceptions"] = true + end + + def boom + raise 'boom!' + end + + def another_boom + raise 'boom!' + end + + def show_detailed_exceptions? + request.local? + end + end + + class ShowExceptionsTest < ActionDispatch::IntegrationTest + test 'show error page from a remote ip' do + @app = ShowExceptionsController.action(:boom) + self.remote_addr = '208.77.188.166' + get '/' + assert_equal "500 error fixture\n", body + end + + test 'show diagnostics from a local ip if show_detailed_exceptions? is set to request.local?' do + @app = ShowExceptionsController.action(:boom) + ['127.0.0.1', '127.0.0.127', '::1', '0:0:0:0:0:0:0:1', '0:0:0:0:0:0:0:1%0'].each do |ip_address| + self.remote_addr = ip_address + get '/' + assert_match(/boom/, body) + end + end + + test 'show diagnostics from a remote ip when env is already set' do + @app = ShowExceptionsController.action(:another_boom) + self.remote_addr = '208.77.188.166' + get '/' + assert_match(/boom/, body) + end + end + + class ShowExceptionsOverridenController < ShowExceptionsController + private + + def show_detailed_exceptions? + params['detailed'] == '1' + end + end + + class ShowExceptionsOverridenTest < ActionDispatch::IntegrationTest + test 'show error page' do + @app = ShowExceptionsOverridenController.action(:boom) + get '/', {'detailed' => '0'} + assert_equal "500 error fixture\n", body + end + + test 'show diagnostics message' do + @app = ShowExceptionsOverridenController.action(:boom) + get '/', {'detailed' => '1'} + assert_match(/boom/, body) + end + end +end diff --git a/actionpack/test/controller/sweeper_test.rb b/actionpack/test/controller/sweeper_test.rb new file mode 100644 index 0000000000..0561efc62f --- /dev/null +++ b/actionpack/test/controller/sweeper_test.rb @@ -0,0 +1,16 @@ +require 'abstract_unit' + + +class SweeperTest < ActionController::TestCase + + class ::AppSweeper < ActionController::Caching::Sweeper; end + + def test_sweeper_should_not_ignore_unknown_method_calls + sweeper = ActionController::Caching::Sweeper.send(:new) + assert_raise NameError do + sweeper.instance_eval do + some_method_that_doesnt_exist + end + end + end +end diff --git a/actionpack/test/controller/test_test.rb b/actionpack/test/controller/test_case_test.rb index cba3aded2f..ecba9fed22 100644 --- a/actionpack/test/controller/test_test.rb +++ b/actionpack/test/controller/test_case_test.rb @@ -1,8 +1,7 @@ require 'abstract_unit' require 'controller/fake_controllers' -require 'active_support/ordered_hash' -class TestTest < ActionController::TestCase +class TestCaseTest < ActionController::TestCase class TestController < ActionController::Base def no_op render :text => 'dummy' @@ -120,13 +119,11 @@ XML def test_assigns @foo = "foo" + @foo_hash = {:foo => :bar} render :nothing => true end private - def rescue_action(e) - raise e - end def generate_url(opts) url_for(opts.merge(:action => "test_uri")) @@ -146,33 +143,68 @@ XML end end + class ViewAssignsController < ActionController::Base + def test_assigns + @foo = "foo" + render :nothing => true + end + + def view_assigns + { "bar" => "bar" } + end + end + def test_raw_post_handling - params = ActiveSupport::OrderedHash[:page, {:name => 'page name'}, 'some key', 123] + params = Hash[:page, {:name => 'page name'}, 'some key', 123] post :render_raw_post, params.dup assert_equal params.to_query, @response.body end def test_body_stream - params = ActiveSupport::OrderedHash[:page, { :name => 'page name' }, 'some key', 123] + params = Hash[:page, { :name => 'page name' }, 'some key', 123] post :render_body, params.dup assert_equal params.to_query, @response.body end + def test_document_body_and_params_with_post + post :test_params, :id => 1 + assert_equal("{\"id\"=>\"1\", \"controller\"=>\"test_case_test/test\", \"action\"=>\"test_params\"}", @response.body) + end + + def test_document_body_with_post + post :render_body, "document body" + assert_equal "document body", @response.body + end + + def test_document_body_with_put + put :render_body, "document body" + assert_equal "document body", @response.body + end + + def test_head + head :test_params + assert_equal 200, @response.status + end + + def test_head_params_as_sting + assert_raise(NoMethodError) { head :test_params, "document body", :id => 10 } + end + def test_process_without_flash process :set_flash assert_equal '><', flash['test'] end def test_process_with_flash - process :set_flash, nil, nil, { "test" => "value" } + process :set_flash, "GET", nil, nil, { "test" => "value" } assert_equal '>value<', flash['test'] end def test_process_with_flash_now - process :set_flash_now, nil, nil, { "test_now" => "value_now" } + process :set_flash_now, "GET", nil, nil, { "test_now" => "value_now" } assert_equal '>value_now<', flash['test_now'] end @@ -185,7 +217,7 @@ XML end def test_process_with_session_arg - process :no_op, nil, { 'string' => 'value1', :symbol => 'value2' } + process :no_op, "GET", nil, { 'string' => 'value1', :symbol => 'value2' } assert_equal 'value1', session['string'] assert_equal 'value1', session[:string] assert_equal 'value2', session['symbol'] @@ -212,22 +244,29 @@ XML def test_process_with_request_uri_with_no_params process :test_uri - assert_equal "/test_test/test/test_uri", @response.body + assert_equal "/test_case_test/test/test_uri", @response.body end def test_process_with_request_uri_with_params - process :test_uri, :id => 7 - assert_equal "/test_test/test/test_uri/7", @response.body + process :test_uri, "GET", :id => 7 + assert_equal "/test_case_test/test/test_uri/7", @response.body + end + + def test_process_with_old_api + assert_deprecated do + process :test_uri, :id => 7 + assert_equal "/test_case_test/test/test_uri/7", @response.body + end end def test_process_with_request_uri_with_params_with_explicit_uri @request.env['PATH_INFO'] = "/explicit/uri" - process :test_uri, :id => 7 + process :test_uri, "GET", :id => 7 assert_equal "/explicit/uri", @response.body end def test_process_with_query_string - process :test_query_string, :q => 'test' + process :test_query_string, "GET", :q => 'test' assert_equal "q=test", @response.body end @@ -239,9 +278,9 @@ XML end def test_multiple_calls - process :test_only_one_param, :left => true + process :test_only_one_param, "GET", :left => true assert_equal "OK", @response.body - process :test_only_one_param, :right => true + process :test_only_one_param, "GET", :right => true assert_equal "OK", @response.body end @@ -254,6 +293,19 @@ XML assert_equal "foo", assigns("foo") assert_equal "foo", assigns[:foo] assert_equal "foo", assigns["foo"] + + # but the assigned variable should not have its own keys stringified + expected_hash = { :foo => :bar } + assert_equal expected_hash, assigns(:foo_hash) + end + + def test_view_assigns + @controller = ViewAssignsController.new + process :test_assigns + assert_equal nil, assigns(:foo) + assert_equal nil, assigns[:foo] + assert_equal "bar", assigns(:bar) + assert_equal "bar", assigns[:bar] end def test_assert_tag_tag @@ -491,7 +543,7 @@ XML get :test_params, :page => {:name => "Page name", :month => '4', :year => '2004', :day => '6'} parsed_params = eval(@response.body) assert_equal( - {'controller' => 'test_test/test', 'action' => 'test_params', + {'controller' => 'test_case_test/test', 'action' => 'test_params', 'page' => {'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6'}}, parsed_params ) @@ -501,7 +553,7 @@ XML get :test_params, :page => {:name => "Page name", :month => 4, :year => 2004, :day => 6} parsed_params = eval(@response.body) assert_equal( - {'controller' => 'test_test/test', 'action' => 'test_params', + {'controller' => 'test_case_test/test', 'action' => 'test_params', 'page' => {'name' => "Page name", 'month' => '4', 'year' => '2004', 'day' => '6'}}, parsed_params ) @@ -513,7 +565,7 @@ XML end parsed_params = eval(@response.body) assert_equal( - {'controller' => 'test_test/test', 'action' => 'test_params', + {'controller' => 'test_case_test/test', 'action' => 'test_params', 'frozen' => 'icy', 'frozens' => ['icy']}, parsed_params ) @@ -533,7 +585,7 @@ XML def test_array_path_parameter_handled_properly with_routing do |set| set.draw do - match 'file/*path', :to => 'test_test/test#test_params' + match 'file/*path', :to => 'test_case_test/test#test_params' match ':controller/:action' end @@ -645,20 +697,15 @@ XML FILES_DIR = File.dirname(__FILE__) + '/../fixtures/multipart' - if RUBY_VERSION < '1.9' - READ_BINARY = 'rb' - READ_PLAIN = 'r' - else - READ_BINARY = 'rb:binary' - READ_PLAIN = 'r:binary' - end + READ_BINARY = 'rb:binary' + READ_PLAIN = 'r:binary' def test_test_uploaded_file filename = 'mona_lisa.jpg' path = "#{FILES_DIR}/#{filename}" content_type = 'image/png' expected = File.read(path) - expected.force_encoding(Encoding::BINARY) if expected.respond_to?(:force_encoding) + expected.force_encoding(Encoding::BINARY) file = Rack::Test::UploadedFile.new(path, content_type) assert_equal filename, file.original_filename @@ -673,7 +720,7 @@ XML end def test_fixture_path_is_accessed_from_self_instead_of_active_support_test_case - TestTest.stubs(:fixture_path).returns(FILES_DIR) + TestCaseTest.stubs(:fixture_path).returns(FILES_DIR) uploaded_file = fixture_file_upload('/mona_lisa.jpg', 'image/png') assert_equal File.open("#{FILES_DIR}/mona_lisa.jpg", READ_PLAIN).read, uploaded_file.read @@ -754,6 +801,22 @@ class CrazyNameTest < ActionController::TestCase end end +class CrazySymbolNameTest < ActionController::TestCase + tests :content + + def test_set_controller_class_using_symbol + assert_equal ContentController, self.class.controller_class + end +end + +class CrazyStringNameTest < ActionController::TestCase + tests 'content' + + def test_set_controller_class_using_string + assert_equal ContentController, self.class.controller_class + end +end + class NamedRoutesControllerTest < ActionController::TestCase tests ContentController diff --git a/actionpack/test/controller/url_for_integration_test.rb b/actionpack/test/controller/url_for_integration_test.rb index 7b734ff0fb..451ea6027d 100644 --- a/actionpack/test/controller/url_for_integration_test.rb +++ b/actionpack/test/controller/url_for_integration_test.rb @@ -3,12 +3,6 @@ require 'abstract_unit' require 'controller/fake_controllers' require 'active_support/core_ext/object/with_options' -module RoutingTestHelpers - def url_for(set, options, recall = nil) - set.send(:url_for, options.merge(:only_path => true, :_path_segments => recall)) - end -end - module ActionPack class URLForIntegrationTest < ActiveSupport::TestCase include RoutingTestHelpers diff --git a/actionpack/test/controller/url_for_test.rb b/actionpack/test/controller/url_for_test.rb index 484e996f31..aa233d6135 100644 --- a/actionpack/test/controller/url_for_test.rb +++ b/actionpack/test/controller/url_for_test.rb @@ -16,6 +16,14 @@ module AbstractController W.default_url_options[:host] = 'www.basecamphq.com' end + def add_port! + W.default_url_options[:port] = 3000 + end + + def add_numeric_host! + W.default_url_options[:host] = '127.0.0.1' + end + def test_exception_is_thrown_without_host assert_raise ArgumentError do W.new.url_for :controller => 'c', :action => 'a', :id => 'i' @@ -67,6 +75,35 @@ module AbstractController ) end + def test_subdomain_may_be_object + model = mock(:to_param => 'api') + add_host! + assert_equal('http://api.basecamphq.com/c/a/i', + W.new.url_for(:subdomain => model, :controller => 'c', :action => 'a', :id => 'i') + ) + end + + def test_subdomain_may_be_removed + add_host! + assert_equal('http://basecamphq.com/c/a/i', + W.new.url_for(:subdomain => false, :controller => 'c', :action => 'a', :id => 'i') + ) + end + + def test_multiple_subdomains_may_be_removed + W.default_url_options[:host] = 'mobile.www.api.basecamphq.com' + assert_equal('http://basecamphq.com/c/a/i', + W.new.url_for(:subdomain => false, :controller => 'c', :action => 'a', :id => 'i') + ) + end + + def test_subdomain_may_be_accepted_with_numeric_host + add_numeric_host! + assert_equal('http://127.0.0.1/c/a/i', + W.new.url_for(:subdomain => 'api', :controller => 'c', :action => 'a', :id => 'i') + ) + end + def test_domain_may_be_changed add_host! assert_equal('http://www.37signals.com/c/a/i', @@ -88,6 +125,14 @@ module AbstractController ) end + def test_default_port + add_host! + add_port! + assert_equal('http://www.basecamphq.com:3000/c/a/i', + W.new.url_for(:controller => 'c', :action => 'a', :id => 'i') + ) + end + def test_protocol add_host! assert_equal('https://www.basecamphq.com/c/a/i', diff --git a/actionpack/test/controller/url_rewriter_test.rb b/actionpack/test/controller/url_rewriter_test.rb index 89de4c1da4..f88903b10e 100644 --- a/actionpack/test/controller/url_rewriter_test.rb +++ b/actionpack/test/controller/url_rewriter_test.rb @@ -70,9 +70,9 @@ class UrlRewriterTests < ActionController::TestCase ) end - def test_anchor_should_be_cgi_escaped + def test_anchor_should_be_uri_escaped assert_equal( - 'http://test.host/c/a/i#anc%2Fhor', + 'http://test.host/c/a/i#anc/hor', @rewriter.rewrite(@routes, :controller => 'c', :action => 'a', :id => 'i', :anchor => Struct.new(:to_param).new('anc/hor')) ) end diff --git a/actionpack/test/controller/view_paths_test.rb b/actionpack/test/controller/view_paths_test.rb index f5ac886c20..40f6dc6f0f 100644 --- a/actionpack/test/controller/view_paths_test.rb +++ b/actionpack/test/controller/view_paths_test.rb @@ -3,7 +3,6 @@ require 'abstract_unit' class ViewLoadPathsTest < ActionController::TestCase class TestController < ActionController::Base def self.controller_path() "test" end - def rescue_action(e) raise end before_filter :add_view_path, :only => :hello_world_at_request_time @@ -16,22 +15,17 @@ class ViewLoadPathsTest < ActionController::TestCase end end - class Test::SubController < ActionController::Base - layout 'test/sub' - def hello_world; render(:template => 'test/hello_world'); end + module Test + class SubController < ActionController::Base + layout 'test/sub' + def hello_world; render(:template => 'test/hello_world'); end + end end def setup - # TestController.view_paths = nil - @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new - @controller = TestController.new - # Following is needed in order to setup @controller.template object properly - @controller.send :assign_shortcuts, @request, @response - @controller.send :initialize_template_class, @response - @paths = TestController.view_paths end diff --git a/actionpack/test/controller/webservice_test.rb b/actionpack/test/controller/webservice_test.rb index ae8588cbb0..351e61eeae 100644 --- a/actionpack/test/controller/webservice_test.rb +++ b/actionpack/test/controller/webservice_test.rb @@ -18,8 +18,6 @@ class WebServiceTest < ActionDispatch::IntegrationTest s << "#{k}#{value}" end end - - def rescue_action(e) raise end end def setup |