aboutsummaryrefslogtreecommitdiffstats
path: root/actionpack/test
diff options
context:
space:
mode:
authorDmitry Polushkin <dmitry.polushkin@gmail.com>2011-12-31 01:10:42 +0000
committerDmitry Polushkin <dmitry.polushkin@gmail.com>2011-12-31 01:10:42 +0000
commit04bc40ff501b1bf81bec7ce3937cb06c896ffc69 (patch)
tree88a33663195900df8a7307aefa2c9aaa561c3973 /actionpack/test
parent84eece0a823e9c601ea99a8709f24605a19bcbfd (diff)
parented17983ec56dec689a0311c7f8fcbeba9874e5a4 (diff)
downloadrails-04bc40ff501b1bf81bec7ce3937cb06c896ffc69.tar.gz
rails-04bc40ff501b1bf81bec7ce3937cb06c896ffc69.tar.bz2
rails-04bc40ff501b1bf81bec7ce3937cb06c896ffc69.zip
Merge branch 'master' of git://github.com/rails/rails
Diffstat (limited to 'actionpack/test')
-rw-r--r--actionpack/test/abstract/layouts_test.rb61
-rw-r--r--actionpack/test/abstract_unit.rb48
-rw-r--r--actionpack/test/activerecord/polymorphic_routes_test.rb22
-rw-r--r--actionpack/test/controller/action_pack_assertions_test.rb19
-rw-r--r--actionpack/test/controller/addresses_render_test.rb4
-rw-r--r--actionpack/test/controller/base_test.rb4
-rw-r--r--actionpack/test/controller/caching_test.rb124
-rw-r--r--actionpack/test/controller/capture_test.rb4
-rw-r--r--actionpack/test/controller/default_url_options_with_filter_test.rb2
-rw-r--r--actionpack/test/controller/flash_hash_test.rb81
-rw-r--r--actionpack/test/controller/flash_test.rb40
-rw-r--r--actionpack/test/controller/force_ssl_test.rb22
-rw-r--r--actionpack/test/controller/http_digest_authentication_test.rb45
-rw-r--r--actionpack/test/controller/layout_test.rb2
-rw-r--r--actionpack/test/controller/log_subscriber_test.rb13
-rw-r--r--actionpack/test/controller/mime_responds_test.rb52
-rw-r--r--actionpack/test/controller/new_base/bare_metal_test.rb6
-rw-r--r--actionpack/test/controller/new_base/render_layout_test.rb36
-rw-r--r--actionpack/test/controller/new_base/render_template_test.rb6
-rw-r--r--actionpack/test/controller/params_wrapper_test.rb62
-rw-r--r--actionpack/test/controller/redirect_test.rb10
-rw-r--r--actionpack/test/controller/render_json_test.rb3
-rw-r--r--actionpack/test/controller/render_test.rb63
-rw-r--r--actionpack/test/controller/rescue_test.rb17
-rw-r--r--actionpack/test/controller/routing_test.rb94
-rw-r--r--actionpack/test/controller/send_file_test.rb2
-rw-r--r--actionpack/test/controller/show_exceptions_test.rb71
-rw-r--r--actionpack/test/controller/test_test.rb11
-rw-r--r--actionpack/test/controller/url_for_integration_test.rb6
-rw-r--r--actionpack/test/controller/url_for_test.rb19
-rw-r--r--actionpack/test/controller/url_rewriter_test.rb4
-rw-r--r--actionpack/test/dispatch/cookies_test.rb102
-rw-r--r--actionpack/test/dispatch/debug_exceptions_test.rb157
-rw-r--r--actionpack/test/dispatch/mime_type_test.rb31
-rw-r--r--actionpack/test/dispatch/mount_test.rb2
-rw-r--r--actionpack/test/dispatch/reloader_test.rb22
-rw-r--r--actionpack/test/dispatch/request/json_params_parsing_test.rb18
-rw-r--r--actionpack/test/dispatch/request/multipart_params_parsing_test.rb2
-rw-r--r--actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb2
-rw-r--r--actionpack/test/dispatch/request/xml_params_parsing_test.rb20
-rw-r--r--actionpack/test/dispatch/request_id_test.rb65
-rw-r--r--actionpack/test/dispatch/request_test.rb33
-rw-r--r--actionpack/test/dispatch/response_test.rb17
-rw-r--r--actionpack/test/dispatch/routing_test.rb94
-rw-r--r--actionpack/test/dispatch/session/cache_store_test.rb181
-rw-r--r--actionpack/test/dispatch/show_exceptions_test.rb131
-rw-r--r--actionpack/test/dispatch/uploaded_file_test.rb8
-rw-r--r--actionpack/test/fixtures/company.rb4
-rw-r--r--actionpack/test/fixtures/developer.rb2
-rw-r--r--actionpack/test/fixtures/functional_caching/fragment_cached.html.erb1
-rw-r--r--actionpack/test/fixtures/test/_content_tag_nested_in_content_tag.erb3
-rw-r--r--actionpack/test/fixtures/test/_label_with_block.erb4
-rw-r--r--actionpack/test/lib/controller/fake_models.rb4
-rw-r--r--actionpack/test/lib/testing_sandbox.rb15
-rw-r--r--actionpack/test/template/active_model_helper_test.rb25
-rw-r--r--actionpack/test/template/capture_helper_test.rb85
-rw-r--r--actionpack/test/template/compiled_templates_test.rb4
-rw-r--r--actionpack/test/template/date_helper_test.rb47
-rw-r--r--actionpack/test/template/form_helper_test.rb164
-rw-r--r--actionpack/test/template/form_options_helper_test.rb36
-rw-r--r--actionpack/test/template/form_tag_helper_test.rb16
-rw-r--r--actionpack/test/template/html-scanner/tag_node_test.rb7
-rw-r--r--actionpack/test/template/javascript_helper_test.rb6
-rw-r--r--actionpack/test/template/lookup_context_test.rb8
-rw-r--r--actionpack/test/template/number_helper_test.rb1
-rw-r--r--actionpack/test/template/output_buffer_test.rb16
-rw-r--r--actionpack/test/template/output_safety_helper_test.rb2
-rw-r--r--actionpack/test/template/record_tag_helper_test.rb6
-rw-r--r--actionpack/test/template/render_test.rb122
-rw-r--r--actionpack/test/template/sanitize_helper_test.rb2
-rw-r--r--actionpack/test/template/sprockets_helper_test.rb16
-rw-r--r--actionpack/test/template/sprockets_helper_with_routes_test.rb57
-rw-r--r--actionpack/test/template/tag_helper_test.rb10
-rw-r--r--actionpack/test/template/template_test.rb100
-rw-r--r--actionpack/test/template/test_test.rb16
-rw-r--r--actionpack/test/template/text_helper_test.rb49
-rw-r--r--actionpack/test/template/translation_helper_test.rb18
77 files changed, 2020 insertions, 664 deletions
diff --git a/actionpack/test/abstract/layouts_test.rb b/actionpack/test/abstract/layouts_test.rb
index 86208899f8..fc25718d9e 100644
--- a/actionpack/test/abstract/layouts_test.rb
+++ b/actionpack/test/abstract/layouts_test.rb
@@ -57,11 +57,8 @@ module AbstractControllerTests
layout "hello_override"
end
- class WithNilChild < WithString
- layout nil
- end
-
class WithStringImpliedChild < WithString
+ layout nil
end
class WithChildOfImplied < WithStringImpliedChild
@@ -141,6 +138,30 @@ module AbstractControllerTests
end
end
+ class WithOnlyConditional < WithStringImpliedChild
+ layout "overwrite", :only => :show
+
+ def index
+ render :template => ActionView::Template::Text.new("Hello index!")
+ end
+
+ def show
+ render :template => ActionView::Template::Text.new("Hello show!")
+ end
+ end
+
+ class WithExceptConditional < WithStringImpliedChild
+ layout "overwrite", :except => :show
+
+ def index
+ render :template => ActionView::Template::Text.new("Hello index!")
+ end
+
+ def show
+ render :template => ActionView::Template::Text.new("Hello show!")
+ end
+ end
+
class TestBase < ActiveSupport::TestCase
test "when no layout is specified, and no default is available, render without a layout" do
controller = Blank.new
@@ -238,12 +259,6 @@ module AbstractControllerTests
assert_equal "With Implied Hello string!", controller.response_body
end
- test "when a child controller specifies layout nil, do not use the parent layout" do
- controller = WithNilChild.new
- controller.process(:index)
- assert_equal "Hello string!", controller.response_body
- end
-
test "when a grandchild has no layout specified, the child has an implied layout, and the " \
"parent has specified a layout, use the child controller layout" do
controller = WithChildOfImplied.new
@@ -260,6 +275,30 @@ module AbstractControllerTests
end
end
end
+
+ test "when specify an :only option which match current action name" do
+ controller = WithOnlyConditional.new
+ controller.process(:show)
+ assert_equal "Overwrite Hello show!", controller.response_body
+ end
+
+ test "when specify an :only option which does not match current action name" do
+ controller = WithOnlyConditional.new
+ controller.process(:index)
+ assert_equal "With Implied Hello index!", controller.response_body
+ end
+
+ test "when specify an :except option which match current action name" do
+ controller = WithExceptConditional.new
+ controller.process(:show)
+ assert_equal "With Implied Hello show!", controller.response_body
+ end
+
+ test "when specify an :except option which does not match current action name" do
+ controller = WithExceptConditional.new
+ controller.process(:index)
+ assert_equal "Overwrite Hello index!", controller.response_body
+ end
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb
index 24d071df39..63109d592a 100644
--- a/actionpack/test/abstract_unit.rb
+++ b/actionpack/test/abstract_unit.rb
@@ -14,14 +14,11 @@ ENV['TMPDIR'] = File.join(File.dirname(__FILE__), 'tmp')
require 'active_support/core_ext/kernel/reporting'
-require 'active_support/core_ext/string/encoding'
-if "ruby".encoding_aware?
- # These are the normal settings that will be set up by Railties
- # TODO: Have these tests support other combinations of these values
- silence_warnings do
- Encoding.default_internal = "UTF-8"
- Encoding.default_external = "UTF-8"
- end
+# These are the normal settings that will be set up by Railties
+# TODO: Have these tests support other combinations of these values
+silence_warnings do
+ Encoding.default_internal = "UTF-8"
+ Encoding.default_external = "UTF-8"
end
require 'test/unit'
@@ -73,7 +70,17 @@ module RackTestUtils
end
module RenderERBUtils
+ def view
+ @view ||= begin
+ path = ActionView::FileSystemResolver.new(FIXTURE_LOAD_PATH)
+ view_paths = ActionView::PathSet.new([path])
+ ActionView::Base.new(view_paths)
+ end
+ end
+
def render_erb(string)
+ @virtual_path = nil
+
template = ActionView::Template.new(
string.strip,
"test template",
@@ -164,7 +171,8 @@ class ActionDispatch::IntegrationTest < ActiveSupport::TestCase
def self.build_app(routes = nil)
RoutedRackApp.new(routes || ActionDispatch::Routing::RouteSet.new) do |middleware|
- middleware.use "ActionDispatch::ShowExceptions"
+ middleware.use "ActionDispatch::ShowExceptions", ActionDispatch::PublicExceptions.new("#{FIXTURE_LOAD_PATH}/public")
+ middleware.use "ActionDispatch::DebugExceptions"
middleware.use "ActionDispatch::Callbacks"
middleware.use "ActionDispatch::ParamsParser"
middleware.use "ActionDispatch::Cookies"
@@ -326,18 +334,18 @@ class Workshop
end
module ActionDispatch
- class ShowExceptions
+ class DebugExceptions
private
- remove_method :public_path
- def public_path
- "#{FIXTURE_LOAD_PATH}/public"
- end
-
- remove_method :logger
- # Silence logger
- def logger
- nil
- end
+ remove_method :stderr_logger
+ # Silence logger
+ def stderr_logger
+ nil
+ end
end
end
+module RoutingTestHelpers
+ def url_for(set, options, recall = nil)
+ set.send(:url_for, options.merge(:only_path => true, :_path_segments => recall))
+ end
+end
diff --git a/actionpack/test/activerecord/polymorphic_routes_test.rb b/actionpack/test/activerecord/polymorphic_routes_test.rb
index 20d11377f6..90e7f4ae59 100644
--- a/actionpack/test/activerecord/polymorphic_routes_test.rb
+++ b/actionpack/test/activerecord/polymorphic_routes_test.rb
@@ -2,42 +2,40 @@ require 'active_record_unit'
require 'fixtures/project'
class Task < ActiveRecord::Base
- set_table_name 'projects'
+ self.table_name = 'projects'
end
class Step < ActiveRecord::Base
- set_table_name 'projects'
+ self.table_name = 'projects'
end
class Bid < ActiveRecord::Base
- set_table_name 'projects'
+ self.table_name = 'projects'
end
class Tax < ActiveRecord::Base
- set_table_name 'projects'
+ self.table_name = 'projects'
end
class Fax < ActiveRecord::Base
- set_table_name 'projects'
+ self.table_name = 'projects'
end
class Series < ActiveRecord::Base
- set_table_name 'projects'
+ self.table_name = 'projects'
end
module Blog
class Post < ActiveRecord::Base
- set_table_name 'projects'
+ self.table_name = 'projects'
end
class Blog < ActiveRecord::Base
- set_table_name 'projects'
+ self.table_name = 'projects'
end
- def self._railtie
- o = Object.new
- def o.railtie_name; "blog" end
- o
+ def self.use_relative_model_naming?
+ true
end
end
diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb
index a714e8bbcc..fab70c71d6 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"
@@ -160,7 +165,7 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
match 'route_one', :to => 'action_pack_assertions#nothing', :as => :route_one
match ':controller/:action'
end
- set.install_helpers
+ set.install_helpers([ActionController::Base, ActionView::Base])
process :redirect_to_named_route
assert_redirected_to 'http://test.host/route_one'
@@ -471,6 +476,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
index c1cd22113d..0b5f2d7679 100644
--- a/actionpack/test/controller/addresses_render_test.rb
+++ b/actionpack/test/controller/addresses_render_test.rb
@@ -1,5 +1,5 @@
require 'abstract_unit'
-require 'logger'
+require 'active_support/logger'
require 'controller/fake_controllers'
class Address
@@ -23,7 +23,7 @@ class AddressesTest < 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/base_test.rb b/actionpack/test/controller/base_test.rb
index 9c22a4e7e0..a4f858d06d 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.
@@ -142,7 +142,7 @@ 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
diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb
index f3b180283f..34a38a5567 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")
@@ -194,6 +234,7 @@ 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
@@ -219,6 +260,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 +291,11 @@ 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
end
class MockTime < Time
@@ -359,6 +410,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 +490,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
@@ -745,6 +818,7 @@ class FunctionalFragmentCachingTest < ActionController::TestCase
expected_body = <<-CACHED
Hello
This bit's fragment cached
+Ciao
CACHED
assert_equal expected_body, @response.body
@@ -786,3 +860,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..a217510434 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
@@ -39,7 +39,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/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/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..d497913dc4 100644
--- a/actionpack/test/controller/flash_test.rb
+++ b/actionpack/test/controller/flash_test.rb
@@ -254,16 +254,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 +270,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..43b20fdead 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
@@ -38,6 +42,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
@@ -80,4 +100,4 @@ class ForceSSLExcludeDevelopmentTest < ActionController::TestCase
get :banana
assert_response 200
end
-end \ No newline at end of file
+end
diff --git a/actionpack/test/controller/http_digest_authentication_test.rb b/actionpack/test/controller/http_digest_authentication_test.rb
index b011536717..a91e3cafa5 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,7 +266,10 @@ 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
diff --git a/actionpack/test/controller/layout_test.rb b/actionpack/test/controller/layout_test.rb
index 25299eb8b8..bc171e201b 100644
--- a/actionpack/test/controller/layout_test.rb
+++ b/actionpack/test/controller/layout_test.rb
@@ -167,7 +167,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
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..76a8c89e60 100644
--- a/actionpack/test/controller/mime_responds_test.rb
+++ b/actionpack/test/controller/mime_responds_test.rb
@@ -509,7 +509,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)
@@ -656,7 +656,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 +747,20 @@ 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_put_with_html_redirects_on_success
with_test_route_set do
put :using_resource
@@ -780,21 +796,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 +824,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 +846,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
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_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_template_test.rb b/actionpack/test/controller/new_base/render_template_test.rb
index ba804421da..ade204c387 100644
--- a/actionpack/test/controller/new_base/render_template_test.rb
+++ b/actionpack/test/controller/new_base/render_template_test.rb
@@ -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
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/redirect_test.rb b/actionpack/test/controller/redirect_test.rb
index 79041055bd..5b739e49ac 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
@@ -216,6 +220,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 aea603b014..768cfb34ac 100644
--- a/actionpack/test/controller/render_test.rb
+++ b/actionpack/test/controller/render_test.rb
@@ -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)
@@ -348,17 +366,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 +382,6 @@ class TestController < ActionController::Base
end
def layout_overriding_layout
- @variable_for_layout = nil
render :action => "hello_world", :layout => "standard"
end
@@ -650,8 +664,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",
@@ -793,9 +810,7 @@ class RenderTest < ActionController::TestCase
end
def test_render_file
- assert_deprecated do
- get :hello_world_file
- end
+ get :hello_world_file
assert_equal "Hello world!", @response.body
end
@@ -1440,6 +1455,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/rescue_test.rb b/actionpack/test/controller/rescue_test.rb
index c445285538..86d6737cbb 100644
--- a/actionpack/test/controller/rescue_test.rb
+++ b/actionpack/test/controller/rescue_test.rb
@@ -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/routing_test.rb b/actionpack/test/controller/routing_test.rb
index 5bf68decca..c9785d9b8a 100644
--- a/actionpack/test/controller/routing_test.rb
+++ b/actionpack/test/controller/routing_test.rb
@@ -11,12 +11,6 @@ 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
include RoutingTestHelpers
@@ -84,11 +78,87 @@ class LegacyRouteSetTests < Test::Unit::TestCase
attr_reader :rs
def setup
- @rs = ::ActionDispatch::Routing::RouteSet.new
+ @rs = ::ActionDispatch::Routing::RouteSet.new
+ @response = nil
end
- def teardown
- @rs.clear!
+ def get(uri_or_host, path = nil, port = nil)
+ host = uri_or_host.host unless path
+ path ||= uri_or_host.path
+
+ params = {'PATH_INFO' => path,
+ 'REQUEST_METHOD' => 'GET',
+ 'HTTP_HOST' => host}
+
+ @rs.call(params)[2].join
+ 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
@@ -413,7 +483,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 })
@@ -719,12 +789,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
diff --git a/actionpack/test/controller/send_file_test.rb b/actionpack/test/controller/send_file_test.rb
index 8f885ff28e..36884846be 100644
--- a/actionpack/test/controller/send_file_test.rb
+++ b/actionpack/test/controller/send_file_test.rb
@@ -61,7 +61,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/test_test.rb b/actionpack/test/controller/test_test.rb
index b64e275363..b3b7ece518 100644
--- a/actionpack/test/controller/test_test.rb
+++ b/actionpack/test/controller/test_test.rb
@@ -665,20 +665,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
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 11ced2df2a..288efbf7c3 100644
--- a/actionpack/test/controller/url_for_test.rb
+++ b/actionpack/test/controller/url_for_test.rb
@@ -16,6 +16,10 @@ module AbstractController
W.default_url_options[:host] = 'www.basecamphq.com'
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 +71,14 @@ 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',
@@ -81,6 +93,13 @@ module AbstractController
)
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',
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/dispatch/cookies_test.rb b/actionpack/test/dispatch/cookies_test.rb
index 49da448001..6ebd02e85c 100644
--- a/actionpack/test/dispatch/cookies_test.rb
+++ b/actionpack/test/dispatch/cookies_test.rb
@@ -210,8 +210,8 @@ class CookiesTest < ActionController::TestCase
assert_equal({"user_name" => "david"}, @response.cookies)
end
- def test_setting_cookie_with_secure_in_development
- Rails.env.stubs(:development?).returns(true)
+ def test_setting_cookie_with_secure_when_always_write_cookie_is_true
+ ActionDispatch::Cookies::CookieJar.any_instance.stubs(:always_write_cookie).returns(true)
get :authenticate_with_secure
assert_cookie_header "user_name=david; path=/; secure"
assert_equal({"user_name" => "david"}, @response.cookies)
@@ -564,100 +564,4 @@ class CookiesTest < ActionController::TestCase
assert_not_equal expected.split("\n"), header
end
end
-end
-
-class CookiesIntegrationTest < ActionDispatch::IntegrationTest
- SessionKey = '_myapp_session'
- SessionSecret = 'b3c631c314c0bbca50c1b2843150fe33'
-
- class TestController < ActionController::Base
- def dont_set_cookies
- head :ok
- end
-
- def set_cookies
- cookies["that"] = "hello"
- head :ok
- end
- end
-
- def test_setting_cookies_raises_after_stream_back_to_client
- with_test_route_set do
- get '/set_cookies'
- assert_raise(ActionDispatch::ClosedError) {
- request.cookie_jar['alert'] = 'alert'
- cookies['alert'] = 'alert'
- }
- end
- end
-
- def test_setting_cookies_raises_after_stream_back_to_client_even_without_cookies
- with_test_route_set do
- get '/dont_set_cookies'
- assert_raise(ActionDispatch::ClosedError) {
- request.cookie_jar['alert'] = 'alert'
- }
- end
- end
-
- def test_setting_permanent_cookies_raises_after_stream_back_to_client
- with_test_route_set do
- get '/set_cookies'
- assert_raise(ActionDispatch::ClosedError) {
- request.cookie_jar.permanent['alert'] = 'alert'
- cookies['alert'] = 'alert'
- }
- end
- end
-
- def test_setting_permanent_cookies_raises_after_stream_back_to_client_even_without_cookies
- with_test_route_set do
- get '/dont_set_cookies'
- assert_raise(ActionDispatch::ClosedError) {
- request.cookie_jar.permanent['alert'] = 'alert'
- }
- end
- end
-
- def test_setting_signed_cookies_raises_after_stream_back_to_client
- with_test_route_set do
- get '/set_cookies'
- assert_raise(ActionDispatch::ClosedError) {
- request.cookie_jar.signed['alert'] = 'alert'
- cookies['alert'] = 'alert'
- }
- end
- end
-
- def test_setting_signed_cookies_raises_after_stream_back_to_client_even_without_cookies
- with_test_route_set do
- get '/dont_set_cookies'
- assert_raise(ActionDispatch::ClosedError) {
- request.cookie_jar.signed['alert'] = 'alert'
- }
- end
- end
-
- private
-
- # Overwrite get to send SessionSecret in env hash
- def get(path, parameters = nil, env = {})
- env["action_dispatch.secret_token"] ||= SessionSecret
- super
- end
-
- def with_test_route_set
- with_routing do |set|
- set.draw do
- match ':action', :to => CookiesIntegrationTest::TestController
- end
-
- @app = self.class.build_app(set) do |middleware|
- middleware.use ActionDispatch::Cookies
- middleware.delete "ActionDispatch::ShowExceptions"
- end
-
- yield
- end
- end
-end
+end \ No newline at end of file
diff --git a/actionpack/test/dispatch/debug_exceptions_test.rb b/actionpack/test/dispatch/debug_exceptions_test.rb
new file mode 100644
index 0000000000..f3dc160d7d
--- /dev/null
+++ b/actionpack/test/dispatch/debug_exceptions_test.rb
@@ -0,0 +1,157 @@
+require 'abstract_unit'
+
+class DebugExceptionsTest < ActionDispatch::IntegrationTest
+
+ class Boomer
+ attr_accessor :closed
+
+ def initialize(detailed = false)
+ @detailed = detailed
+ @closed = false
+ end
+
+ def each
+ end
+
+ def close
+ @closed = true
+ end
+
+ def call(env)
+ env['action_dispatch.show_detailed_exceptions'] = @detailed
+ req = ActionDispatch::Request.new(env)
+ case req.path
+ when "/pass"
+ [404, { "X-Cascade" => "pass" }, self]
+ when "/not_found"
+ raise ActionController::UnknownAction
+ when "/runtime_error"
+ raise RuntimeError
+ when "/method_not_allowed"
+ raise ActionController::MethodNotAllowed
+ when "/not_implemented"
+ raise ActionController::NotImplemented
+ when "/unprocessable_entity"
+ raise ActionController::InvalidAuthenticityToken
+ when "/not_found_original_exception"
+ raise ActionView::Template::Error.new('template', {}, AbstractController::ActionNotFound.new)
+ else
+ raise "puke!"
+ end
+ end
+ end
+
+ ProductionApp = ActionDispatch::DebugExceptions.new(Boomer.new(false))
+ DevelopmentApp = ActionDispatch::DebugExceptions.new(Boomer.new(true))
+
+ test 'skip diagnosis if not showing detailed exceptions' do
+ @app = ProductionApp
+ assert_raise RuntimeError do
+ get "/", {}, {'action_dispatch.show_exceptions' => true}
+ end
+ end
+
+ test 'skip diagnosis if not showing exceptions' do
+ @app = DevelopmentApp
+ assert_raise RuntimeError do
+ get "/", {}, {'action_dispatch.show_exceptions' => false}
+ end
+ end
+
+ test 'raise an exception on cascade pass' do
+ @app = ProductionApp
+ assert_raise ActionController::RoutingError do
+ get "/pass", {}, {'action_dispatch.show_exceptions' => true}
+ end
+ end
+
+ test 'closes the response body on cascade pass' do
+ boomer = Boomer.new(false)
+ @app = ActionDispatch::DebugExceptions.new(boomer)
+ assert_raise ActionController::RoutingError do
+ get "/pass", {}, {'action_dispatch.show_exceptions' => true}
+ end
+ assert boomer.closed, "Expected to close the response body"
+ end
+
+ test "rescue with diagnostics message" do
+ @app = DevelopmentApp
+
+ get "/", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 500
+ assert_match(/puke/, body)
+
+ get "/not_found", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 404
+ assert_match(/#{ActionController::UnknownAction.name}/, body)
+
+ get "/method_not_allowed", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 405
+ assert_match(/ActionController::MethodNotAllowed/, body)
+ end
+
+ test "does not show filtered parameters" do
+ @app = DevelopmentApp
+
+ get "/", {"foo"=>"bar"}, {'action_dispatch.show_exceptions' => true,
+ 'action_dispatch.parameter_filter' => [:foo]}
+ assert_response 500
+ assert_match("&quot;foo&quot;=&gt;&quot;[FILTERED]&quot;", body)
+ end
+
+ test "show registered original exception for wrapped exceptions" do
+ @app = DevelopmentApp
+
+ get "/not_found_original_exception", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 404
+ assert_match(/AbstractController::ActionNotFound/, body)
+ end
+
+ test "show the controller name in the diagnostics template when controller name is present" do
+ @app = DevelopmentApp
+ get("/runtime_error", {}, {
+ 'action_dispatch.show_exceptions' => true,
+ 'action_dispatch.request.parameters' => {
+ 'action' => 'show',
+ 'id' => 'unknown',
+ 'controller' => 'featured_tile'
+ }
+ })
+ assert_response 500
+ assert_match(/RuntimeError\n in FeaturedTileController/, body)
+ end
+
+ test "sets the HTTP charset parameter" do
+ @app = DevelopmentApp
+
+ get "/", {}, {'action_dispatch.show_exceptions' => true}
+ assert_equal "text/html; charset=utf-8", response.headers["Content-Type"]
+ end
+
+ test 'uses logger from env' do
+ @app = DevelopmentApp
+ output = StringIO.new
+ get "/", {}, {'action_dispatch.show_exceptions' => true, 'action_dispatch.logger' => Logger.new(output)}
+ assert_match(/puke/, output.rewind && output.read)
+ end
+
+ test 'uses backtrace cleaner from env' do
+ @app = DevelopmentApp
+ cleaner = stub(:clean => ['passed backtrace cleaner'])
+ get "/", {}, {'action_dispatch.show_exceptions' => true, 'action_dispatch.backtrace_cleaner' => cleaner}
+ assert_match(/passed backtrace cleaner/, body)
+ end
+
+ test 'logs exception backtrace when all lines silenced' do
+ output = StringIO.new
+ backtrace_cleaner = ActiveSupport::BacktraceCleaner.new
+ backtrace_cleaner.add_silencer { true }
+
+ env = {'action_dispatch.show_exceptions' => true,
+ 'action_dispatch.logger' => Logger.new(output),
+ 'action_dispatch.backtrace_cleaner' => backtrace_cleaner}
+
+ get "/", {}, env
+ assert_operator((output.rewind && output.read).lines.count, :>, 10)
+ end
+end
diff --git a/actionpack/test/dispatch/mime_type_test.rb b/actionpack/test/dispatch/mime_type_test.rb
index 08fe2127b9..db21080c42 100644
--- a/actionpack/test/dispatch/mime_type_test.rb
+++ b/actionpack/test/dispatch/mime_type_test.rb
@@ -95,6 +95,37 @@ class MimeTypeTest < ActiveSupport::TestCase
end
end
+ test "custom type with type aliases" do
+ begin
+ Mime::Type.register "text/foobar", :foobar, ["text/foo", "text/bar"]
+ %w[text/foobar text/foo text/bar].each do |type|
+ assert_equal Mime::FOOBAR, type
+ end
+ ensure
+ Mime::Type.unregister(:FOOBAR)
+ end
+ end
+
+ test "custom type with extension aliases" do
+ begin
+ Mime::Type.register "text/foobar", :foobar, [], [:foo, "bar"]
+ %w[foobar foo bar].each do |extension|
+ assert_equal Mime::FOOBAR, Mime::EXTENSION_LOOKUP[extension]
+ end
+ ensure
+ Mime::Type.unregister(:FOOBAR)
+ end
+ end
+
+ test "register alias" do
+ begin
+ Mime::Type.register_alias "application/xhtml+xml", :foobar
+ assert_equal Mime::HTML, Mime::EXTENSION_LOOKUP['foobar']
+ ensure
+ Mime::Type.unregister(:FOOBAR)
+ end
+ end
+
test "type should be equal to symbol" do
assert_equal Mime::HTML, 'application/xhtml+xml'
assert_equal Mime::HTML, :html
diff --git a/actionpack/test/dispatch/mount_test.rb b/actionpack/test/dispatch/mount_test.rb
index 1a032539b9..f7a746120e 100644
--- a/actionpack/test/dispatch/mount_test.rb
+++ b/actionpack/test/dispatch/mount_test.rb
@@ -51,4 +51,4 @@ class TestRoutingMount < ActionDispatch::IntegrationTest
get "/fakeengine"
assert_equal "OK", response.body
end
-end \ No newline at end of file
+end
diff --git a/actionpack/test/dispatch/reloader_test.rb b/actionpack/test/dispatch/reloader_test.rb
index eaabc1feb3..3411bd14ea 100644
--- a/actionpack/test/dispatch/reloader_test.rb
+++ b/actionpack/test/dispatch/reloader_test.rb
@@ -43,6 +43,19 @@ class ReloaderTest < Test::Unit::TestCase
assert_respond_to body, :close
end
+ def test_condition_specifies_when_to_reload
+ i, j = 0, 0, 0, 0
+ Reloader.to_prepare { |*args| i += 1 }
+ Reloader.to_cleanup { |*args| j += 1 }
+ app = Reloader.new(lambda { |env| [200, {}, []] }, lambda { i < 3 })
+ 5.times do
+ resp = app.call({})
+ resp[2].close
+ end
+ assert_equal 3, i
+ assert_equal 3, j
+ end
+
def test_returned_body_object_behaves_like_underlying_object
body = call_and_return_body do
b = MyBody.new
@@ -116,6 +129,15 @@ class ReloaderTest < Test::Unit::TestCase
assert cleaned
end
+ def test_prepend_prepare_callback
+ i = 10
+ Reloader.to_prepare { i += 1 }
+ Reloader.to_prepare(:prepend => true) { i = 0 }
+
+ Reloader.prepare!
+ assert_equal 1, i
+ end
+
def test_cleanup_callbacks_are_called_on_exceptions
cleaned = false
Reloader.to_cleanup { cleaned = true }
diff --git a/actionpack/test/dispatch/request/json_params_parsing_test.rb b/actionpack/test/dispatch/request/json_params_parsing_test.rb
index d854d55173..ad44b4b16a 100644
--- a/actionpack/test/dispatch/request/json_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/json_params_parsing_test.rb
@@ -32,13 +32,21 @@ class JsonParamsParsingTest < ActionDispatch::IntegrationTest
test "logs error if parsing unsuccessful" do
with_test_routing do
+ output = StringIO.new
+ json = "[\"person]\": {\"name\": \"David\"}}"
+ post "/parse", json, {'CONTENT_TYPE' => 'application/json', 'action_dispatch.show_exceptions' => true, 'action_dispatch.logger' => Logger.new(output)}
+ assert_response :error
+ output.rewind && err = output.read
+ assert err =~ /Error occurred while parsing request parameters/
+ end
+ end
+
+ test "occurring a parse error if parsing unsuccessful" do
+ with_test_routing do
begin
- $stderr = StringIO.new
+ $stderr = StringIO.new # suppress the log
json = "[\"person]\": {\"name\": \"David\"}}"
- post "/parse", json, {'CONTENT_TYPE' => 'application/json', 'action_dispatch.show_exceptions' => true}
- assert_response :error
- $stderr.rewind && err = $stderr.read
- assert err =~ /Error occurred while parsing request parameters/
+ assert_raise(MultiJson::DecodeError) { post "/parse", json, {'CONTENT_TYPE' => 'application/json', 'action_dispatch.show_exceptions' => false} }
ensure
$stderr = STDERR
end
diff --git a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
index 560ea00923..d144f013f5 100644
--- a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
@@ -89,7 +89,7 @@ class MultipartParamsParsingTest < ActionDispatch::IntegrationTest
# Rack doesn't handle multipart/mixed for us.
files = params['files']
- files.force_encoding('ASCII-8BIT') if files.respond_to?(:force_encoding)
+ files.force_encoding('ASCII-8BIT')
assert_equal 19756, files.size
end
diff --git a/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb b/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb
index 04a0fb6f34..05569561d2 100644
--- a/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb
@@ -146,8 +146,6 @@ class UrlEncodedParamsParsingTest < ActionDispatch::IntegrationTest
end
def assert_utf8(object)
- return unless "ruby".encoding_aware?
-
correct_encoding = Encoding.default_internal
unless object.is_a?(Hash)
diff --git a/actionpack/test/dispatch/request/xml_params_parsing_test.rb b/actionpack/test/dispatch/request/xml_params_parsing_test.rb
index 38453dfe48..d8fa751548 100644
--- a/actionpack/test/dispatch/request/xml_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/xml_params_parsing_test.rb
@@ -54,13 +54,21 @@ class XmlParamsParsingTest < ActionDispatch::IntegrationTest
test "logs error if parsing unsuccessful" do
with_test_routing do
+ output = StringIO.new
+ xml = "<person><name>David</name><avatar type='file' name='me.jpg' content_type='image/jpg'>#{ActiveSupport::Base64.encode64('ABC')}</avatar></pineapple>"
+ post "/parse", xml, default_headers.merge('action_dispatch.show_exceptions' => true, 'action_dispatch.logger' => Logger.new(output))
+ assert_response :error
+ output.rewind && err = output.read
+ assert err =~ /Error occurred while parsing request parameters/
+ end
+ end
+
+ test "occurring a parse error if parsing unsuccessful" do
+ with_test_routing do
begin
- $stderr = StringIO.new
- xml = "<person><name>David</name><avatar type='file' name='me.jpg' content_type='image/jpg'>#{ActiveSupport::Base64.encode64('ABC')}</avatar></pineapple>"
- post "/parse", xml, default_headers.merge('action_dispatch.show_exceptions' => true)
- assert_response :error
- $stderr.rewind && err = $stderr.read
- assert err =~ /Error occurred while parsing request parameters/
+ $stderr = StringIO.new # suppress the log
+ xml = "<person><name>David</name></pineapple>"
+ assert_raise(REXML::ParseException) { post "/parse", xml, default_headers.merge('action_dispatch.show_exceptions' => false) }
ensure
$stderr = STDERR
end
diff --git a/actionpack/test/dispatch/request_id_test.rb b/actionpack/test/dispatch/request_id_test.rb
new file mode 100644
index 0000000000..4b98cd32f2
--- /dev/null
+++ b/actionpack/test/dispatch/request_id_test.rb
@@ -0,0 +1,65 @@
+require 'abstract_unit'
+
+class RequestIdTest < ActiveSupport::TestCase
+ test "passing on the request id from the outside" do
+ assert_equal "external-uu-rid", stub_request('HTTP_X_REQUEST_ID' => 'external-uu-rid').uuid
+ end
+
+ test "ensure that only alphanumeric uurids are accepted" do
+ assert_equal "X-Hacked-HeaderStuff", stub_request('HTTP_X_REQUEST_ID' => '; X-Hacked-Header: Stuff').uuid
+ end
+
+ test "ensure that 255 char limit on the request id is being enforced" do
+ assert_equal "X" * 255, stub_request('HTTP_X_REQUEST_ID' => 'X' * 500).uuid
+ end
+
+ test "generating a request id when none is supplied" do
+ assert_match(/\w+-\w+-\w+-\w+-\w+/, stub_request.uuid)
+ end
+
+ private
+
+ def stub_request(env = {})
+ ActionDispatch::RequestId.new(lambda { |environment| [ 200, environment, [] ] }).call(env)
+ ActionDispatch::Request.new(env)
+ end
+end
+
+class RequestIdResponseTest < ActionDispatch::IntegrationTest
+ class TestController < ActionController::Base
+ def index
+ head :ok
+ end
+ end
+
+ test "request id is passed all the way to the response" do
+ with_test_route_set do
+ get '/'
+ assert_match(/\w+/, @response.headers["X-Request-Id"])
+ end
+ end
+
+ test "request id given on request is passed all the way to the response" do
+ with_test_route_set do
+ get '/', {}, 'HTTP_X_REQUEST_ID' => 'X' * 500
+ assert_equal "X" * 255, @response.headers["X-Request-Id"]
+ end
+ end
+
+
+ private
+
+ def with_test_route_set
+ with_routing do |set|
+ set.draw do
+ match '/', :to => ::RequestIdResponseTest::TestController.action(:index)
+ end
+
+ @app = self.class.build_app(set) do |middleware|
+ middleware.use ActionDispatch::RequestId
+ end
+
+ yield
+ end
+ end
+end \ No newline at end of file
diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb
index a611252b31..5b3d38c48c 100644
--- a/actionpack/test/dispatch/request_test.rb
+++ b/actionpack/test/dispatch/request_test.rb
@@ -36,7 +36,7 @@ class RequestTest < ActiveSupport::TestCase
request = stub_request 'REMOTE_ADDR' => '1.2.3.4',
'HTTP_X_FORWARDED_FOR' => '3.4.5.6'
- assert_equal '1.2.3.4', request.remote_ip
+ assert_equal '3.4.5.6', request.remote_ip
request = stub_request 'REMOTE_ADDR' => '127.0.0.1',
'HTTP_X_FORWARDED_FOR' => '3.4.5.6'
@@ -89,6 +89,11 @@ class RequestTest < ActiveSupport::TestCase
assert_equal '9.9.9.9', request.remote_ip
end
+ test "remote ip when the remote ip middleware returns nil" do
+ request = stub_request 'REMOTE_ADDR' => '127.0.0.1'
+ assert_equal '127.0.0.1', request.remote_ip
+ end
+
test "remote ip with user specified trusted proxies" do
@trusted_proxies = /^67\.205\.106\.73$/i
@@ -106,7 +111,7 @@ class RequestTest < ActiveSupport::TestCase
request = stub_request 'REMOTE_ADDR' => '67.205.106.74,172.16.0.1',
'HTTP_X_FORWARDED_FOR' => '3.4.5.6'
- assert_equal '67.205.106.74', request.remote_ip
+ assert_equal '3.4.5.6', request.remote_ip
request = stub_request 'HTTP_X_FORWARDED_FOR' => 'unknown,67.205.106.73'
assert_equal 'unknown', request.remote_ip
@@ -613,6 +618,30 @@ class RequestTest < ActiveSupport::TestCase
assert_equal "/authenticate?secret", path
end
+ test "original_fullpath returns ORIGINAL_FULLPATH" do
+ request = stub_request('ORIGINAL_FULLPATH' => "/foo?bar")
+
+ path = request.original_fullpath
+ assert_equal "/foo?bar", path
+ end
+
+ test "original_url returns url built using ORIGINAL_FULLPATH" do
+ request = stub_request('ORIGINAL_FULLPATH' => "/foo?bar",
+ 'HTTP_HOST' => "example.org",
+ 'rack.url_scheme' => "http")
+
+ url = request.original_url
+ assert_equal "http://example.org/foo?bar", url
+ end
+
+ test "original_fullpath returns fullpath if ORIGINAL_FULLPATH is not present" do
+ request = stub_request('PATH_INFO' => "/foo",
+ 'QUERY_STRING' => "bar")
+
+ path = request.original_fullpath
+ assert_equal "/foo?bar", path
+ end
+
protected
def stub_request(env = {})
diff --git a/actionpack/test/dispatch/response_test.rb b/actionpack/test/dispatch/response_test.rb
index 5abbaf74fe..82d1200f8e 100644
--- a/actionpack/test/dispatch/response_test.rb
+++ b/actionpack/test/dispatch/response_test.rb
@@ -5,6 +5,12 @@ class ResponseTest < ActiveSupport::TestCase
@response = ActionDispatch::Response.new
end
+ def test_response_body_encoding
+ body = ["hello".encode('utf-8')]
+ response = ActionDispatch::Response.new 200, {}, body
+ assert_equal Encoding::UTF_8, response.body.encoding
+ end
+
test "simple output" do
@response.body = "Hello, World!"
@@ -130,6 +136,17 @@ class ResponseTest < ActiveSupport::TestCase
assert_equal('application/xml; charset=utf-16', resp.headers['Content-Type'])
end
+
+ test "read content type without charset" do
+ original = ActionDispatch::Response.default_charset
+ begin
+ ActionDispatch::Response.default_charset = 'utf-16'
+ resp = ActionDispatch::Response.new(200, { "Content-Type" => "text/xml" })
+ assert_equal('utf-16', resp.charset)
+ ensure
+ ActionDispatch::Response.default_charset = original
+ end
+ end
end
class ResponseIntegrationTest < ActionDispatch::IntegrationTest
diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb
index c0b74bc9f9..d5c1586600 100644
--- a/actionpack/test/dispatch/routing_test.rb
+++ b/actionpack/test/dispatch/routing_test.rb
@@ -62,13 +62,8 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
match 'secure', :to => redirect("/secure/login")
match 'mobile', :to => redirect(:subdomain => 'mobile')
- match 'documentation', :to => redirect(:domain => 'example-documentation.com', :path => '')
- match 'new_documentation', :to => redirect(:path => '/documentation/new')
match 'super_new_documentation', :to => redirect(:host => 'super-docs.com')
- match 'stores/:name', :to => redirect(:subdomain => 'stores', :path => '/%{name}')
- match 'stores/:name(*rest)', :to => redirect(:subdomain => 'stores', :path => '/%{name}%{rest}')
-
match 'youtube_favorites/:youtube_id/:name', :to => redirect(YoutubeFavoritesRedirector)
constraints(lambda { |req| true }) do
@@ -79,7 +74,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
match 'sign_in' => "sessions#new"
match 'account/modulo/:name', :to => redirect("/%{name}s")
- match 'account/proc/:name', :to => redirect {|params| "/#{params[:name].pluralize}" }
+ match 'account/proc/:name', :to => redirect {|params, req| "/#{params[:name].pluralize}" }
match 'account/proc_req' => redirect {|params, req| "/#{req.method}" }
match 'account/google' => redirect('http://www.google.com/', :status => 302)
@@ -96,6 +91,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
match "/local/:action", :controller => "local"
match "/projects/status(.:format)"
+ match "/404", :to => lambda { |env| [404, {"Content-Type" => "text/plain"}, ["NOT FOUND"]] }
constraints(:ip => /192\.168\.1\.\d\d\d/) do
get 'admin' => "queenbee#index"
@@ -339,6 +335,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
scope '(:locale)', :locale => /en|pl/ do
+ get "registrations/new"
resources :descriptions
root :to => 'projects#index'
end
@@ -710,20 +707,6 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
- def test_redirect_hash_with_domain_and_path
- with_test_routes do
- get '/documentation'
- verify_redirect 'http://www.example-documentation.com'
- end
- end
-
- def test_redirect_hash_with_path
- with_test_routes do
- get '/new_documentation'
- verify_redirect 'http://www.example.com/documentation/new'
- end
- end
-
def test_redirect_hash_with_host
with_test_routes do
get '/super_new_documentation?section=top'
@@ -731,20 +714,6 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
- def test_redirect_hash_path_substitution
- with_test_routes do
- get '/stores/iernest'
- verify_redirect 'http://stores.example.com/iernest'
- end
- end
-
- def test_redirect_hash_path_substitution_with_catch_all
- with_test_routes do
- get '/stores/iernest/products'
- verify_redirect 'http://stores.example.com/iernest/products'
- end
- end
-
def test_redirect_class
with_test_routes do
get '/youtube_favorites/oHg5SJYRHA0/rick-rolld'
@@ -1471,6 +1440,16 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
end
+ def test_nested_optional_path_shorthand
+ with_test_routes do
+ get '/registrations/new'
+ assert @request.params[:locale].nil?
+
+ get '/en/registrations/new'
+ assert 'en', @request.params[:locale]
+ end
+ end
+
def test_default_params
with_test_routes do
get '/inline_pages'
@@ -2318,7 +2297,12 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
def test_named_routes_collision_is_avoided_unless_explicitly_given_as
assert_equal "/c/1", routes_collision_path(1)
- assert_equal "/forced_collision", routes_forced_collision_path
+ assert_equal "/fc", routes_forced_collision_path
+ end
+
+ def test_redirect_argument_error
+ routes = Class.new { include ActionDispatch::Routing::Redirection }.new
+ assert_raises(ArgumentError) { routes.redirect Object.new }
end
def test_explicitly_avoiding_the_named_route
@@ -2430,7 +2414,8 @@ class TestAppendingRoutes < ActionDispatch::IntegrationTest
lambda { |e| [ 200, { 'Content-Type' => 'text/plain' }, [resp] ] }
end
- setup do
+ def setup
+ super
s = self
@app = ActionDispatch::Routing::RouteSet.new
@app.append do
@@ -2517,3 +2502,40 @@ class TestHttpMethods < ActionDispatch::IntegrationTest
end
end
end
+
+class TestUriPathEscaping < ActionDispatch::IntegrationTest
+ Routes = ActionDispatch::Routing::RouteSet.new.tap do |app|
+ app.draw do
+ match '/:segment' => lambda { |env|
+ path_params = env['action_dispatch.request.path_parameters']
+ [200, { 'Content-Type' => 'text/plain' }, [path_params[:segment]]]
+ }, :as => :segment
+
+ match '/*splat' => lambda { |env|
+ path_params = env['action_dispatch.request.path_parameters']
+ [200, { 'Content-Type' => 'text/plain' }, [path_params[:splat]]]
+ }, :as => :splat
+ end
+ end
+
+ include Routes.url_helpers
+ def app; Routes end
+
+ test 'escapes generated path segment' do
+ assert_equal '/a%20b/c+d', segment_path(:segment => 'a b/c+d')
+ end
+
+ test 'unescapes recognized path segment' do
+ get '/a%20b%2Fc+d'
+ assert_equal 'a b/c+d', @response.body
+ end
+
+ test 'escapes generated path splat' do
+ assert_equal '/a%20b/c+d', splat_path(:splat => 'a b/c+d')
+ end
+
+ test 'unescapes recognized path splat' do
+ get '/a%20b/c+d'
+ assert_equal 'a b/c+d', @response.body
+ end
+end
diff --git a/actionpack/test/dispatch/session/cache_store_test.rb b/actionpack/test/dispatch/session/cache_store_test.rb
new file mode 100644
index 0000000000..73e056de23
--- /dev/null
+++ b/actionpack/test/dispatch/session/cache_store_test.rb
@@ -0,0 +1,181 @@
+require 'abstract_unit'
+
+class CacheStoreTest < ActionDispatch::IntegrationTest
+ class TestController < ActionController::Base
+ def no_session_access
+ head :ok
+ end
+
+ def set_session_value
+ session[:foo] = "bar"
+ head :ok
+ end
+
+ def set_serialized_session_value
+ session[:foo] = SessionAutoloadTest::Foo.new
+ head :ok
+ end
+
+ def get_session_value
+ render :text => "foo: #{session[:foo].inspect}"
+ end
+
+ def get_session_id
+ render :text => "#{request.session_options[:id]}"
+ end
+
+ def call_reset_session
+ session[:bar]
+ reset_session
+ session[:bar] = "baz"
+ head :ok
+ end
+
+ def rescue_action(e) raise end
+ end
+
+ def test_setting_and_getting_session_value
+ with_test_route_set do
+ get '/set_session_value'
+ assert_response :success
+ assert cookies['_session_id']
+
+ get '/get_session_value'
+ assert_response :success
+ assert_equal 'foo: "bar"', response.body
+ end
+ end
+
+ def test_getting_nil_session_value
+ with_test_route_set do
+ get '/get_session_value'
+ assert_response :success
+ assert_equal 'foo: nil', response.body
+ end
+ end
+
+ def test_getting_session_value_after_session_reset
+ with_test_route_set do
+ get '/set_session_value'
+ assert_response :success
+ assert cookies['_session_id']
+ session_cookie = cookies.send(:hash_for)['_session_id']
+
+ get '/call_reset_session'
+ assert_response :success
+ assert_not_equal [], headers['Set-Cookie']
+
+ cookies << session_cookie # replace our new session_id with our old, pre-reset session_id
+
+ get '/get_session_value'
+ assert_response :success
+ assert_equal 'foo: nil', response.body, "data for this session should have been obliterated from cache"
+ end
+ end
+
+ def test_getting_from_nonexistent_session
+ with_test_route_set do
+ get '/get_session_value'
+ assert_response :success
+ assert_equal 'foo: nil', response.body
+ assert_nil cookies['_session_id'], "should only create session on write, not read"
+ end
+ end
+
+ def test_setting_session_value_after_session_reset
+ with_test_route_set do
+ get '/set_session_value'
+ assert_response :success
+ assert cookies['_session_id']
+ session_id = cookies['_session_id']
+
+ get '/call_reset_session'
+ assert_response :success
+ assert_not_equal [], headers['Set-Cookie']
+
+ get '/get_session_value'
+ assert_response :success
+ assert_equal 'foo: nil', response.body
+
+ get '/get_session_id'
+ assert_response :success
+ assert_not_equal session_id, response.body
+ end
+ end
+
+ def test_getting_session_id
+ with_test_route_set do
+ get '/set_session_value'
+ assert_response :success
+ assert cookies['_session_id']
+ session_id = cookies['_session_id']
+
+ get '/get_session_id'
+ assert_response :success
+ assert_equal session_id, response.body, "should be able to read session id without accessing the session hash"
+ end
+ end
+
+ def test_deserializes_unloaded_class
+ with_test_route_set do
+ with_autoload_path "session_autoload_test" do
+ get '/set_serialized_session_value'
+ assert_response :success
+ assert cookies['_session_id']
+ end
+ with_autoload_path "session_autoload_test" do
+ get '/get_session_id'
+ assert_response :success
+ end
+ with_autoload_path "session_autoload_test" do
+ get '/get_session_value'
+ assert_response :success
+ assert_equal 'foo: #<SessionAutoloadTest::Foo bar:"baz">', response.body, "should auto-load unloaded class"
+ end
+ end
+ end
+
+ def test_doesnt_write_session_cookie_if_session_id_is_already_exists
+ with_test_route_set do
+ get '/set_session_value'
+ assert_response :success
+ assert cookies['_session_id']
+
+ get '/get_session_value'
+ assert_response :success
+ assert_equal nil, headers['Set-Cookie'], "should not resend the cookie again if session_id cookie is already exists"
+ end
+ end
+
+ def test_prevents_session_fixation
+ with_test_route_set do
+ get '/get_session_value'
+ assert_response :success
+ assert_equal 'foo: nil', response.body
+ session_id = cookies['_session_id']
+
+ reset!
+
+ get '/set_session_value', :_session_id => session_id
+ assert_response :success
+ assert_not_equal session_id, cookies['_session_id']
+ end
+ end
+
+ private
+ def with_test_route_set
+ with_routing do |set|
+ set.draw do
+ match ':action', :to => ::CacheStoreTest::TestController
+ end
+
+ @app = self.class.build_app(set) do |middleware|
+ cache = ActiveSupport::Cache::MemoryStore.new
+ middleware.use ActionDispatch::Session::CacheStore, :key => '_session_id', :cache => cache
+ middleware.delete "ActionDispatch::ShowExceptions"
+ end
+
+ yield
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/show_exceptions_test.rb b/actionpack/test/dispatch/show_exceptions_test.rb
index 42f6c7f79f..e9504f3524 100644
--- a/actionpack/test/dispatch/show_exceptions_test.rb
+++ b/actionpack/test/dispatch/show_exceptions_test.rb
@@ -2,32 +2,33 @@ require 'abstract_unit'
class ShowExceptionsTest < ActionDispatch::IntegrationTest
- Boomer = lambda do |env|
- req = ActionDispatch::Request.new(env)
- case req.path
- when "/not_found"
- raise ActionController::UnknownAction
- when "/runtime_error"
- raise RuntimeError
- when "/method_not_allowed"
- raise ActionController::MethodNotAllowed
- when "/not_implemented"
- raise ActionController::NotImplemented
- when "/unprocessable_entity"
- raise ActionController::InvalidAuthenticityToken
- when "/not_found_original_exception"
- raise ActionView::Template::Error.new('template', {}, AbstractController::ActionNotFound.new)
- else
- raise "puke!"
+ class Boomer
+ def call(env)
+ req = ActionDispatch::Request.new(env)
+ case req.path
+ when "/not_found"
+ raise ActionController::UnknownAction
+ when "/method_not_allowed"
+ raise ActionController::MethodNotAllowed
+ when "/not_found_original_exception"
+ raise ActionView::Template::Error.new('template', {}, AbstractController::ActionNotFound.new)
+ else
+ raise "puke!"
+ end
end
end
- ProductionApp = ActionDispatch::ShowExceptions.new(Boomer, false)
- DevelopmentApp = ActionDispatch::ShowExceptions.new(Boomer, true)
+ ProductionApp = ActionDispatch::ShowExceptions.new(Boomer.new, ActionDispatch::PublicExceptions.new("#{FIXTURE_LOAD_PATH}/public"))
- test "rescue in public from a remote ip" do
+ test "skip exceptions app if not showing exceptions" do
+ @app = ProductionApp
+ assert_raise RuntimeError do
+ get "/", {}, {'action_dispatch.show_exceptions' => false}
+ end
+ end
+
+ test "rescue with error page" do
@app = ProductionApp
- self.remote_addr = '208.77.188.166'
get "/", {}, {'action_dispatch.show_exceptions' => true}
assert_response 500
@@ -42,32 +43,11 @@ class ShowExceptionsTest < ActionDispatch::IntegrationTest
assert_equal "", body
end
- test "rescue locally from a local request" do
- @app = ProductionApp
- ['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 "/", {}, {'action_dispatch.show_exceptions' => true}
- assert_response 500
- assert_match(/puke/, body)
-
- get "/not_found", {}, {'action_dispatch.show_exceptions' => true}
- assert_response 404
- assert_match(/#{ActionController::UnknownAction.name}/, body)
-
- get "/method_not_allowed", {}, {'action_dispatch.show_exceptions' => true}
- assert_response 405
- assert_match(/ActionController::MethodNotAllowed/, body)
- end
- end
-
- test "localize public rescue message" do
- # Change locale
+ test "localize rescue error page" do
old_locale, I18n.locale = I18n.locale, :da
begin
@app = ProductionApp
- self.remote_addr = '208.77.188.166'
get "/", {}, {'action_dispatch.show_exceptions' => true}
assert_response 500
@@ -81,67 +61,42 @@ class ShowExceptionsTest < ActionDispatch::IntegrationTest
end
end
- test "always rescue locally in development mode" do
- @app = DevelopmentApp
- self.remote_addr = '208.77.188.166'
+ test "sets the HTTP charset parameter" do
+ @app = ProductionApp
get "/", {}, {'action_dispatch.show_exceptions' => true}
- assert_response 500
- assert_match(/puke/, body)
-
- get "/not_found", {}, {'action_dispatch.show_exceptions' => true}
- assert_response 404
- assert_match(/#{ActionController::UnknownAction.name}/, body)
-
- get "/method_not_allowed", {}, {'action_dispatch.show_exceptions' => true}
- assert_response 405
- assert_match(/ActionController::MethodNotAllowed/, body)
- end
-
- test "does not show filtered parameters" do
- @app = DevelopmentApp
-
- get "/", {"foo"=>"bar"}, {'action_dispatch.show_exceptions' => true,
- 'action_dispatch.parameter_filter' => [:foo]}
- assert_response 500
- assert_match("&quot;foo&quot;=&gt;&quot;[FILTERED]&quot;", body)
+ assert_equal "text/html; charset=utf-8", response.headers["Content-Type"]
end
- test "show registered original exception for wrapped exceptions when consider_all_requests_local is false" do
+ test "show registered original exception for wrapped exceptions" do
@app = ProductionApp
- self.remote_addr = '208.77.188.166'
get "/not_found_original_exception", {}, {'action_dispatch.show_exceptions' => true}
assert_response 404
assert_match(/404 error/, body)
end
- test "show registered original exception for wrapped exceptions when consider_all_requests_local is true" do
- @app = DevelopmentApp
+ test "calls custom exceptions app" do
+ exceptions_app = lambda do |env|
+ assert_kind_of AbstractController::ActionNotFound, env["action_dispatch.exception"]
+ assert_equal "/404", env["PATH_INFO"]
+ [404, { "Content-Type" => "text/plain" }, ["YOU FAILED BRO"]]
+ end
+ @app = ActionDispatch::ShowExceptions.new(Boomer.new, exceptions_app)
get "/not_found_original_exception", {}, {'action_dispatch.show_exceptions' => true}
assert_response 404
- assert_match(/AbstractController::ActionNotFound/, body)
- end
-
- test "show the controller name in the diagnostics template when controller name is present" do
- @app = ProductionApp
- get("/runtime_error", {}, {
- 'action_dispatch.show_exceptions' => true,
- 'action_dispatch.request.parameters' => {
- 'action' => 'show',
- 'id' => 'unknown',
- 'controller' => 'featured_tile'
- }
- })
- assert_response 500
- assert_match(/RuntimeError\n in FeaturedTileController/, body)
+ assert_equal "YOU FAILED BRO", body
end
- test "sets the HTTP charset parameter" do
- @app = DevelopmentApp
+ test "returns an empty response if custom exceptions app returns X-Cascade pass" do
+ exceptions_app = lambda do |env|
+ [404, { "X-Cascade" => "pass" }, []]
+ end
- get "/", {}, {'action_dispatch.show_exceptions' => true}
- assert_equal "text/html; charset=utf-8", response.headers["Content-Type"]
+ @app = ActionDispatch::ShowExceptions.new(Boomer.new, exceptions_app)
+ get "/method_not_allowed", {}, {'action_dispatch.show_exceptions' => true}
+ assert_response 405
+ assert_equal "", body
end
end
diff --git a/actionpack/test/dispatch/uploaded_file_test.rb b/actionpack/test/dispatch/uploaded_file_test.rb
index 7e4a1519fb..0b95291e18 100644
--- a/actionpack/test/dispatch/uploaded_file_test.rb
+++ b/actionpack/test/dispatch/uploaded_file_test.rb
@@ -13,11 +13,9 @@ module ActionDispatch
assert_equal 'foo', uf.original_filename
end
- if "ruby".encoding_aware?
- def test_filename_should_be_in_utf_8
- uf = Http::UploadedFile.new(:filename => 'foo', :tempfile => Object.new)
- assert_equal "UTF-8", uf.original_filename.encoding.to_s
- end
+ def test_filename_should_be_in_utf_8
+ uf = Http::UploadedFile.new(:filename => 'foo', :tempfile => Object.new)
+ assert_equal "UTF-8", uf.original_filename.encoding.to_s
end
def test_content_type
diff --git a/actionpack/test/fixtures/company.rb b/actionpack/test/fixtures/company.rb
index cd39ea7898..e29978801e 100644
--- a/actionpack/test/fixtures/company.rb
+++ b/actionpack/test/fixtures/company.rb
@@ -1,10 +1,10 @@
class Company < ActiveRecord::Base
has_one :mascot
attr_protected :rating
- set_sequence_name :companies_nonstd_seq
+ self.sequence_name = :companies_nonstd_seq
validates_presence_of :name
def validate
errors.add('rating', 'rating should not be 2') if rating == 2
end
-end \ No newline at end of file
+end
diff --git a/actionpack/test/fixtures/developer.rb b/actionpack/test/fixtures/developer.rb
index c70eda34c6..dd14548fac 100644
--- a/actionpack/test/fixtures/developer.rb
+++ b/actionpack/test/fixtures/developer.rb
@@ -5,5 +5,5 @@ class Developer < ActiveRecord::Base
end
class DeVeLoPeR < ActiveRecord::Base
- set_table_name "developers"
+ self.table_name = "developers"
end
diff --git a/actionpack/test/fixtures/functional_caching/fragment_cached.html.erb b/actionpack/test/fixtures/functional_caching/fragment_cached.html.erb
index c479adb897..fa5e6bd318 100644
--- a/actionpack/test/fixtures/functional_caching/fragment_cached.html.erb
+++ b/actionpack/test/fixtures/functional_caching/fragment_cached.html.erb
@@ -1,2 +1,3 @@
Hello
<%= cache do %>This bit's fragment cached<% end %>
+<%= 'Ciao' %>
diff --git a/actionpack/test/fixtures/test/_content_tag_nested_in_content_tag.erb b/actionpack/test/fixtures/test/_content_tag_nested_in_content_tag.erb
new file mode 100644
index 0000000000..2f21a75dd9
--- /dev/null
+++ b/actionpack/test/fixtures/test/_content_tag_nested_in_content_tag.erb
@@ -0,0 +1,3 @@
+<%= content_tag 'p' do %>
+ <%= content_tag 'b', 'Hello' %>
+<% end %>
diff --git a/actionpack/test/fixtures/test/_label_with_block.erb b/actionpack/test/fixtures/test/_label_with_block.erb
new file mode 100644
index 0000000000..40117e594e
--- /dev/null
+++ b/actionpack/test/fixtures/test/_label_with_block.erb
@@ -0,0 +1,4 @@
+<%= label 'post', 'message' do %>
+ Message
+ <%= text_field 'post', 'message' %>
+<% end %>
diff --git a/actionpack/test/lib/controller/fake_models.rb b/actionpack/test/lib/controller/fake_models.rb
index 363403092b..f2362714d7 100644
--- a/actionpack/test/lib/controller/fake_models.rb
+++ b/actionpack/test/lib/controller/fake_models.rb
@@ -175,8 +175,8 @@ class HashBackedAuthor < Hash
end
module Blog
- def self._railtie
- self
+ def self.use_relative_model_naming?
+ true
end
class Post < Struct.new(:title, :id)
diff --git a/actionpack/test/lib/testing_sandbox.rb b/actionpack/test/lib/testing_sandbox.rb
deleted file mode 100644
index c36585104f..0000000000
--- a/actionpack/test/lib/testing_sandbox.rb
+++ /dev/null
@@ -1,15 +0,0 @@
-module TestingSandbox
- # Temporarily replaces KCODE for the block
- def with_kcode(kcode)
- if RUBY_VERSION < '1.9'
- old_kcode, $KCODE = $KCODE, kcode
- begin
- yield
- ensure
- $KCODE = old_kcode
- end
- else
- yield
- end
- end
-end
diff --git a/actionpack/test/template/active_model_helper_test.rb b/actionpack/test/template/active_model_helper_test.rb
index 8530a72a82..52be0f1762 100644
--- a/actionpack/test/template/active_model_helper_test.rb
+++ b/actionpack/test/template/active_model_helper_test.rb
@@ -4,7 +4,7 @@ class ActiveModelHelperTest < ActionView::TestCase
tests ActionView::Helpers::ActiveModelHelper
silence_warnings do
- class Post < Struct.new(:author_name, :body)
+ class Post < Struct.new(:author_name, :body, :updated_at)
include ActiveModel::Conversion
include ActiveModel::Validations
@@ -20,9 +20,11 @@ class ActiveModelHelperTest < ActionView::TestCase
@post = Post.new
@post.errors[:author_name] << "can't be empty"
@post.errors[:body] << "foo"
+ @post.errors[:updated_at] << "bar"
@post.author_name = ""
@post.body = "Back to the hill and over it again!"
+ @post.updated_at = Date.new(2004, 6, 15)
end
def test_text_area_with_errors
@@ -39,6 +41,27 @@ class ActiveModelHelperTest < ActionView::TestCase
)
end
+ def test_date_select_with_errors
+ assert_dom_equal(
+ %(<div class="field_with_errors"><select id="post_updated_at_1i" name="post[updated_at(1i)]">\n<option selected="selected" value="2004">2004</option>\n<option value="2005">2005</option>\n</select>\n<input id="post_updated_at_2i" name="post[updated_at(2i)]" type="hidden" value="6" />\n<input id="post_updated_at_3i" name="post[updated_at(3i)]" type="hidden" value="15" />\n</div>),
+ date_select("post", "updated_at", :discard_month => true, :discard_day => true, :start_year => 2004, :end_year => 2005)
+ )
+ end
+
+ def test_datetime_select_with_errors
+ assert_dom_equal(
+ %(<div class="field_with_errors"><input id="post_updated_at_1i" name="post[updated_at(1i)]" type="hidden" value="2004" />\n<input id="post_updated_at_2i" name="post[updated_at(2i)]" type="hidden" value="6" />\n<input id="post_updated_at_3i" name="post[updated_at(3i)]" type="hidden" value="15" />\n<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n<option selected="selected" value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n</select>\n : <select id="post_updated_at_5i" name="post[updated_at(5i)]">\n<option selected="selected" value="00">00</option>\n</select>\n</div>),
+ datetime_select("post", "updated_at", :discard_year => true, :discard_month => true, :discard_day => true, :minute_step => 60)
+ )
+ end
+
+ def test_time_select_with_errors
+ assert_dom_equal(
+ %(<div class="field_with_errors"><input id="post_updated_at_1i" name="post[updated_at(1i)]" type="hidden" value="2004" />\n<input id="post_updated_at_2i" name="post[updated_at(2i)]" type="hidden" value="6" />\n<input id="post_updated_at_3i" name="post[updated_at(3i)]" type="hidden" value="15" />\n<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n<option selected="selected" value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n</select>\n : <select id="post_updated_at_5i" name="post[updated_at(5i)]">\n<option selected="selected" value="00">00</option>\n</select>\n</div>),
+ time_select("post", "updated_at", :minute_step => 60)
+ )
+ end
+
def test_hidden_field_does_not_render_errors
assert_dom_equal(
%(<input id="post_author_name" name="post[author_name]" type="hidden" value="" />),
diff --git a/actionpack/test/template/capture_helper_test.rb b/actionpack/test/template/capture_helper_test.rb
index 13e2d5b595..17469f8c3e 100644
--- a/actionpack/test/template/capture_helper_test.rb
+++ b/actionpack/test/template/capture_helper_test.rb
@@ -53,6 +53,13 @@ class CaptureHelperTest < ActionView::TestCase
assert_equal 'foobar', content_for(:title)
end
+ def test_content_for_with_multiple_calls_and_flush
+ assert ! content_for?(:title)
+ content_for :title, 'foo'
+ content_for :title, 'bar', true
+ assert_equal 'bar', content_for(:title)
+ end
+
def test_content_for_with_block
assert ! content_for?(:title)
content_for :title do
@@ -63,6 +70,39 @@ class CaptureHelperTest < ActionView::TestCase
assert_equal 'foobar', content_for(:title)
end
+ def test_content_for_with_block_and_multiple_calls_with_flush
+ assert ! content_for?(:title)
+ content_for :title do
+ 'foo'
+ end
+ content_for :title, true do
+ 'bar'
+ end
+ assert_equal 'bar', content_for(:title)
+ end
+
+ def test_content_for_with_block_and_multiple_calls_with_flush_nil_content
+ assert ! content_for?(:title)
+ content_for :title do
+ 'foo'
+ end
+ content_for :title, nil, true do
+ 'bar'
+ end
+ assert_equal 'bar', content_for(:title)
+ end
+
+ def test_content_for_with_block_and_multiple_calls_without_flush
+ assert ! content_for?(:title)
+ content_for :title do
+ 'foo'
+ end
+ content_for :title, false do
+ 'bar'
+ end
+ assert_equal 'foobar', content_for(:title)
+ end
+
def test_content_for_with_whitespace_block
assert ! content_for?(:title)
content_for :title, 'foo'
@@ -74,12 +114,27 @@ class CaptureHelperTest < ActionView::TestCase
assert_equal 'foobar', content_for(:title)
end
+ def test_content_for_with_whitespace_block_and_flush
+ assert ! content_for?(:title)
+ content_for :title, 'foo'
+ content_for :title, true do
+ output_buffer << " \n "
+ nil
+ end
+ content_for :title, 'bar', true
+ assert_equal 'bar', content_for(:title)
+ end
+
def test_content_for_returns_nil_when_writing
assert ! content_for?(:title)
assert_equal nil, content_for(:title, 'foo')
assert_equal nil, content_for(:title) { output_buffer << 'bar'; nil }
assert_equal nil, content_for(:title) { output_buffer << " \n "; nil }
assert_equal 'foobar', content_for(:title)
+ assert_equal nil, content_for(:title, 'foo', true)
+ assert_equal nil, content_for(:title, true) { output_buffer << 'bar'; nil }
+ assert_equal nil, content_for(:title, true) { output_buffer << " \n "; nil }
+ assert_equal 'bar', content_for(:title)
end
def test_content_for_question_mark
@@ -131,17 +186,15 @@ class CaptureHelperTest < ActionView::TestCase
assert buffer.equal?(@av.output_buffer)
end
- unless RUBY_VERSION < '1.9'
- def test_with_output_buffer_sets_proper_encoding
- @av.output_buffer = ActionView::OutputBuffer.new
+ def test_with_output_buffer_sets_proper_encoding
+ @av.output_buffer = ActionView::OutputBuffer.new
- # Ensure we set the output buffer to an encoding different than the default one.
- alt_encoding = alt_encoding(@av.output_buffer)
- @av.output_buffer.force_encoding(alt_encoding)
+ # Ensure we set the output buffer to an encoding different than the default one.
+ alt_encoding = alt_encoding(@av.output_buffer)
+ @av.output_buffer.force_encoding(alt_encoding)
- @av.with_output_buffer do
- assert_equal alt_encoding, @av.output_buffer.encoding
- end
+ @av.with_output_buffer do
+ assert_equal alt_encoding, @av.output_buffer.encoding
end
end
@@ -165,14 +218,12 @@ class CaptureHelperTest < ActionView::TestCase
assert_equal '', view.output_buffer
end
- unless RUBY_VERSION < '1.9'
- def test_flush_output_buffer_preserves_the_encoding_of_the_output_buffer
- view = view_with_controller
- alt_encoding = alt_encoding(view.output_buffer)
- view.output_buffer.force_encoding(alt_encoding)
- flush_output_buffer
- assert_equal alt_encoding, view.output_buffer.encoding
- end
+ def test_flush_output_buffer_preserves_the_encoding_of_the_output_buffer
+ view = view_with_controller
+ alt_encoding = alt_encoding(view.output_buffer)
+ view.output_buffer.force_encoding(alt_encoding)
+ flush_output_buffer
+ assert_equal alt_encoding, view.output_buffer.encoding
end
def alt_encoding(output_buffer)
diff --git a/actionpack/test/template/compiled_templates_test.rb b/actionpack/test/template/compiled_templates_test.rb
index 8fc78283d8..30d798d693 100644
--- a/actionpack/test/template/compiled_templates_test.rb
+++ b/actionpack/test/template/compiled_templates_test.rb
@@ -3,6 +3,10 @@ require 'controller/fake_models'
class CompiledTemplatesTest < Test::Unit::TestCase
def setup
+ # Clean up any details key cached to expose failures
+ # that otherwise would appear just on isolated tests
+ ActionView::LookupContext::DetailsKey.clear
+
@compiled_templates = ActionView::CompiledTemplates
@compiled_templates.instance_methods.each do |m|
@compiled_templates.send(:remove_method, m) if m =~ /^_render_template_/
diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb
index 09c53a36f0..fadfb59572 100644
--- a/actionpack/test/template/date_helper_test.rb
+++ b/actionpack/test/template/date_helper_test.rb
@@ -164,6 +164,15 @@ class DateHelperTest < ActionView::TestCase
assert_dom_equal expected, select_day(nil, :include_blank => true)
end
+ def test_select_day_with_two_digit_numbers
+ expected = %(<select id="date_day" name="date[day]">\n)
+ expected << %(<option value="1">01</option>\n<option selected="selected" value="2">02</option>\n<option value="3">03</option>\n<option value="4">04</option>\n<option value="5">05</option>\n<option value="6">06</option>\n<option value="7">07</option>\n<option value="8">08</option>\n<option value="9">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_day(Time.mktime(2011, 8, 2), :use_two_digit_numbers => true)
+ assert_dom_equal expected, select_day(2, :use_two_digit_numbers => true)
+ end
+
def test_select_day_with_html_options
expected = %(<select id="date_day" name="date[day]" class="selector">\n)
expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n)
@@ -198,6 +207,15 @@ class DateHelperTest < ActionView::TestCase
assert_dom_equal expected, select_month(8)
end
+ def test_select_month_with_two_digit_numbers
+ expected = %(<select id="date_month" name="date[month]">\n)
+ expected << %(<option value="1">01</option>\n<option value="2">02</option>\n<option value="3">03</option>\n<option value="4">04</option>\n<option value="5">05</option>\n<option value="6">06</option>\n<option value="7">07</option>\n<option value="8" selected="selected">08</option>\n<option value="9">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n)
+ expected << "</select>\n"
+
+ assert_dom_equal expected, select_month(Time.mktime(2011, 8, 16), :use_two_digit_numbers => true)
+ assert_dom_equal expected, select_month(8, :use_two_digit_numbers => true)
+ end
+
def test_select_month_with_disabled
expected = %(<select id="date_month" name="date[month]" disabled="disabled">\n)
expected << %(<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
@@ -664,6 +682,15 @@ class DateHelperTest < ActionView::TestCase
assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), :start_year => 2003, :end_year => 2005, :prefix => "date[first]")
end
+ def test_select_date_with_too_big_range_between_start_year_and_end_year
+ assert_raise(ArgumentError) { select_date(Time.mktime(2003, 8, 16), :start_year => 2000, :end_year => 20000, :prefix => "date[first]", :order => [:month, :day, :year]) }
+ assert_raise(ArgumentError) { select_date(Time.mktime(2003, 8, 16), :start_year => Date.today.year - 100.years, :end_year => 2000, :prefix => "date[first]", :order => [:month, :day, :year]) }
+ end
+
+ def test_select_date_can_have_more_then_1000_years_interval_if_forced_via_parameter
+ assert_nothing_raised { select_date(Time.mktime(2003, 8, 16), :start_year => 2000, :end_year => 3100, :max_years_allowed => 2000) }
+ end
+
def test_select_date_with_order
expected = %(<select id="date_first_month" name="date[first][month]">\n)
expected << %(<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
@@ -977,7 +1004,6 @@ class DateHelperTest < ActionView::TestCase
assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), :start_year => 2003, :end_year => 2005, :prefix => "date[first]", :ampm => true)
end
-
def test_select_datetime_with_separators
expected = %(<select id="date_first_year" name="date[first][year]">\n)
expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
@@ -1370,6 +1396,25 @@ class DateHelperTest < ActionView::TestCase
assert_dom_equal expected, date_select("post", "written_on", :order => [ :month, :year ])
end
+ def test_date_select_without_day_with_separator
+ @post = Post.new
+ @post.written_on = Date.new(2004, 6, 15)
+
+ expected = "<input type=\"hidden\" id=\"post_written_on_3i\" name=\"post[written_on(3i)]\" value=\"1\" />\n"
+
+ expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n}
+ expected << %{<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n}
+ expected << "</select>\n"
+
+ expected << "/"
+
+ expected << %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}
+ expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n}
+ expected << "</select>\n"
+
+ assert_dom_equal expected, date_select("post", "written_on", :date_separator => '/', :order => [ :month, :year ])
+ end
+
def test_date_select_without_day_and_with_disabled_html_option
@post = Post.new
@post.written_on = Date.new(2004, 6, 15)
diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb
index e36d032f6c..73b936b16e 100644
--- a/actionpack/test/template/form_helper_test.rb
+++ b/actionpack/test/template/form_helper_test.rb
@@ -3,6 +3,8 @@ require 'controller/fake_models'
require 'active_support/core_ext/object/inclusion'
class FormHelperTest < ActionView::TestCase
+ include RenderERBUtils
+
tests ActionView::Helpers::FormHelper
def form_for(*)
@@ -27,7 +29,13 @@ class FormHelperTest < ActionView::TestCase
:body => "Write entire text here",
:color => {
:red => "Rojo"
+ },
+ :comments => {
+ :body => "Write body here"
}
+ },
+ :tag => {
+ :value => "Tag"
}
}
}
@@ -68,6 +76,12 @@ class FormHelperTest < ActionView::TestCase
@post.secret = 1
@post.written_on = Date.new(2004, 6, 15)
+ @post.comments = []
+ @post.comments << @comment
+
+ @post.tags = []
+ @post.tags << Tag.new
+
@blog_post = Blog::Post.new("And his name will be forty and four.", 44)
end
@@ -151,6 +165,40 @@ class FormHelperTest < ActionView::TestCase
I18n.locale = old_locale
end
+ def test_label_with_locales_and_nested_attributes
+ old_locale, I18n.locale = I18n.locale, :label
+ form_for(@post, :html => { :id => 'create-post' }) do |f|
+ f.fields_for(:comments) do |cf|
+ concat cf.label(:body)
+ end
+ end
+
+ expected = whole_form("/posts/123", "create-post" , "edit_post", :method => "put") do
+ "<label for=\"post_comments_attributes_0_body\">Write body here</label>"
+ end
+
+ assert_dom_equal expected, output_buffer
+ ensure
+ I18n.locale = old_locale
+ end
+
+ def test_label_with_locales_fallback_and_nested_attributes
+ old_locale, I18n.locale = I18n.locale, :label
+ form_for(@post, :html => { :id => 'create-post' }) do |f|
+ f.fields_for(:tags) do |cf|
+ concat cf.label(:value)
+ end
+ end
+
+ expected = whole_form("/posts/123", "create-post" , "edit_post", :method => "put") do
+ "<label for=\"post_tags_attributes_0_value\">Tag</label>"
+ end
+
+ assert_dom_equal expected, output_buffer
+ ensure
+ I18n.locale = old_locale
+ end
+
def test_label_with_for_attribute_as_symbol
assert_dom_equal('<label for="my_for">Title</label>', label(:post, :title, nil, :for => "my_for"))
end
@@ -184,6 +232,10 @@ class FormHelperTest < ActionView::TestCase
assert_dom_equal('<label for="post_title">The title, please:</label>', label(:post, :title) { "The title, please:" })
end
+ def test_label_with_block_in_erb
+ assert_equal "<label for=\"post_message\">\n Message\n <input id=\"post_message\" name=\"post[message]\" size=\"30\" type=\"text\" />\n</label>", view.render("test/label_with_block")
+ end
+
def test_text_field
assert_dom_equal(
'<input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />', text_field("post", "title")
@@ -438,13 +490,17 @@ class FormHelperTest < ActionView::TestCase
end
def test_number_field
- expected = %{<input name="order[quantity]" size="30" max="9" id="order_quantity" type="number" min="1" />}
+ expected = %{<input name="order[quantity]" max="9" id="order_quantity" type="number" min="1" />}
assert_dom_equal(expected, number_field("order", "quantity", :in => 1...10))
+ expected = %{<input name="order[quantity]" size="30" max="9" id="order_quantity" type="number" min="1" />}
+ assert_dom_equal(expected, number_field("order", "quantity", :size => 30, :in => 1...10))
end
def test_range_input
- expected = %{<input name="hifi[volume]" step="0.1" size="30" max="11" id="hifi_volume" type="range" min="0" />}
+ expected = %{<input name="hifi[volume]" step="0.1" max="11" id="hifi_volume" type="range" min="0" />}
assert_dom_equal(expected, range_field("hifi", "volume", :in => 0..11, :step => 0.1))
+ expected = %{<input name="hifi[volume]" step="0.1" size="30" max="11" id="hifi_volume" type="range" min="0" />}
+ assert_dom_equal(expected, range_field("hifi", "volume", :size => 30, :in => 0..11, :step => 0.1))
end
def test_explicit_name
@@ -633,6 +689,7 @@ class FormHelperTest < ActionView::TestCase
concat f.text_area(:body)
concat f.check_box(:secret)
concat f.submit('Create post')
+ concat f.button('Create post')
end
expected = whole_form("/posts/123", "create-post" , "edit_post", :method => "put") do
@@ -641,7 +698,8 @@ class FormHelperTest < ActionView::TestCase
"<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
"<input name='post[secret]' type='hidden' value='0' />" +
"<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" +
- "<input name='commit' type='submit' value='Create post' />"
+ "<input name='commit' type='submit' value='Create post' />" +
+ "<button name='button' type='submit'>Create post</button>"
end
assert_dom_equal expected, output_buffer
@@ -690,7 +748,7 @@ class FormHelperTest < ActionView::TestCase
assert_dom_equal expected, output_buffer
end
- def test_form_for_with_isolated_namespaced_model
+ def test_form_for_with_model_using_relative_model_naming
form_for(@blog_post) do |f|
concat f.text_field :title
concat f.submit('Edit post')
@@ -713,7 +771,7 @@ class FormHelperTest < ActionView::TestCase
concat f.submit('Create post')
end
- expected = whole_form("/posts/123", "create-post", "other_name_edit", :method => "put") do
+ expected = whole_form("/posts/123", "create-post", "edit_other_name", :method => "put") do
"<label for='other_name_title' class='post_title'>Title</label>" +
"<input name='other_name[title]' size='30' id='other_name_title' value='Hello World' type='text' />" +
"<textarea name='other_name[body]' id='other_name_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
@@ -850,7 +908,7 @@ class FormHelperTest < ActionView::TestCase
concat f.check_box(:secret)
end
- expected = whole_form('/posts/123', 'post[]_edit', 'post[]_edit', 'put') do
+ expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', 'put') do
"<label for='post_123_title'>Title</label>" +
"<input name='post[123][title]' size='30' type='text' id='post_123_title' value='Hello World' />" +
"<textarea name='post[123][body]' id='post_123_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
@@ -868,7 +926,7 @@ class FormHelperTest < ActionView::TestCase
concat f.check_box(:secret)
end
- expected = whole_form('/posts/123', 'post[]_edit', 'post[]_edit', 'put') do
+ expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', 'put') do
"<input name='post[][title]' size='30' type='text' id='post__title' value='Hello World' />" +
"<textarea name='post[][body]' id='post__body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
"<input name='post[][secret]' type='hidden' value='0' />" +
@@ -878,6 +936,82 @@ class FormHelperTest < ActionView::TestCase
assert_dom_equal expected, output_buffer
end
+ def test_form_for_with_namespace
+ form_for(@post, :namespace => 'namespace') do |f|
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.check_box(:secret)
+ end
+
+ expected = whole_form('/posts/123', 'namespace_edit_post_123', 'edit_post', 'put') do
+ "<input name='post[title]' size='30' type='text' id='namespace_post_title' value='Hello World' />" +
+ "<textarea name='post[body]' id='namespace_post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
+ "<input name='post[secret]' type='hidden' value='0' />" +
+ "<input name='post[secret]' checked='checked' type='checkbox' id='namespace_post_secret' value='1' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_with_namespace_with_label
+ form_for(@post, :namespace => 'namespace') do |f|
+ concat f.label(:title)
+ concat f.text_field(:title)
+ end
+
+ expected = whole_form('/posts/123', 'namespace_edit_post_123', 'edit_post', 'put') do
+ "<label for='namespace_post_title'>Title</label>" +
+ "<input name='post[title]' size='30' type='text' id='namespace_post_title' value='Hello World' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_two_form_for_with_namespace
+ form_for(@post, :namespace => 'namespace_1') do |f|
+ concat f.label(:title)
+ concat f.text_field(:title)
+ end
+
+ expected_1 = whole_form('/posts/123', 'namespace_1_edit_post_123', 'edit_post', 'put') do
+ "<label for='namespace_1_post_title'>Title</label>" +
+ "<input name='post[title]' size='30' type='text' id='namespace_1_post_title' value='Hello World' />"
+ end
+
+ assert_dom_equal expected_1, output_buffer
+
+ form_for(@post, :namespace => 'namespace_2') do |f|
+ concat f.label(:title)
+ concat f.text_field(:title)
+ end
+
+ expected_2 = whole_form('/posts/123', 'namespace_2_edit_post_123', 'edit_post', 'put') do
+ "<label for='namespace_2_post_title'>Title</label>" +
+ "<input name='post[title]' size='30' type='text' id='namespace_2_post_title' value='Hello World' />"
+ end
+
+ assert_dom_equal expected_2, output_buffer
+ end
+
+ def test_fields_for_with_namespace
+ @comment.body = 'Hello World'
+ form_for(@post, :namespace => 'namespace') do |f|
+ concat f.text_field(:title)
+ concat f.text_area(:body)
+ concat f.fields_for(@comment) { |c|
+ concat c.text_field(:body)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'namespace_edit_post_123', 'edit_post', 'put') do
+ "<input name='post[title]' size='30' type='text' id='namespace_post_title' value='Hello World' />" +
+ "<textarea name='post[body]' id='namespace_post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
+ "<input name='post[comment][body]' size='30' type='text' id='namespace_post_comment_body' value='Hello World' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
def test_submit_with_object_as_new_record_and_locale_strings
old_locale, I18n.locale = I18n.locale, :submit
@@ -934,7 +1068,7 @@ class FormHelperTest < ActionView::TestCase
concat f.submit
end
- expected = whole_form('/posts/123', 'another_post_edit', 'another_post_edit', :method => 'put') do
+ expected = whole_form('/posts/123', 'edit_another_post', 'edit_another_post', :method => 'put') do
"<input name='commit' type='submit' value='Update your Post' />"
end
@@ -966,7 +1100,7 @@ class FormHelperTest < ActionView::TestCase
}
end
- expected = whole_form('/posts/123', 'post[]_edit', 'post[]_edit', 'put') do
+ expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', 'put') do
"<input name='post[123][title]' size='30' type='text' id='post_123_title' value='Hello World' />" +
"<input name='post[123][comment][][name]' size='30' type='text' id='post_123_comment__name' value='new comment' />"
end
@@ -1025,7 +1159,7 @@ class FormHelperTest < ActionView::TestCase
}
end
- expected = whole_form('/posts/123', 'post[]_edit', 'post[]_edit', 'put') do
+ expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', 'put') do
"<input name='post[123][comment][title]' size='30' type='text' id='post_123_comment_title' value='Hello World' />"
end
@@ -1053,7 +1187,7 @@ class FormHelperTest < ActionView::TestCase
}
end
- expected = whole_form('/posts/123', 'post[]_edit', 'post[]_edit', 'put') do
+ expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', 'put') do
"<input name='post[123][comment][123][title]' size='30' type='text' id='post_123_comment_123_title' value='Hello World' />"
end
@@ -1073,9 +1207,9 @@ class FormHelperTest < ActionView::TestCase
}
end
- expected = whole_form('/posts/123', 'post[]_edit', 'post[]_edit', 'put') do
+ expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', 'put') do
"<input name='post[123][comment][5][title]' size='30' type='text' id='post_123_comment_5_title' value='Hello World' />"
- end + whole_form('/posts/123', 'post_edit', 'post_edit', 'put') do
+ end + whole_form('/posts/123', 'edit_post', 'edit_post', 'put') do
"<input name='post[1][comment][123][title]' size='30' type='text' id='post_1_comment_123_title' value='Hello World' />"
end
@@ -1728,7 +1862,7 @@ class FormHelperTest < ActionView::TestCase
}
end
- expected = whole_form('/posts/123', 'create-post', 'post_edit', :method => 'put') do
+ expected = whole_form('/posts/123', 'create-post', 'edit_post', :method => 'put') do
"<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
"<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
"<input name='parent_post[secret]' type='hidden' value='0' />" +
@@ -1748,7 +1882,7 @@ class FormHelperTest < ActionView::TestCase
}
end
- expected = whole_form('/posts/123', 'create-post', 'post_edit', :method => 'put') do
+ expected = whole_form('/posts/123', 'create-post', 'edit_post', :method => 'put') do
"<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
"<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
"<input name='post[comment][name]' type='text' id='post_comment_name' value='new comment' size='30' />"
diff --git a/actionpack/test/template/form_options_helper_test.rb b/actionpack/test/template/form_options_helper_test.rb
index 6aea991f7c..4a889beadd 100644
--- a/actionpack/test/template/form_options_helper_test.rb
+++ b/actionpack/test/template/form_options_helper_test.rb
@@ -587,6 +587,42 @@ class FormOptionsHelperTest < ActionView::TestCase
)
end
+ def test_empty
+ @post = Post.new
+ @post.category = ""
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"\"></option>\n</select>",
+ select("post", "category", [], :prompt => true, :include_blank => true)
+ )
+ end
+
+ def test_select_with_nil
+ @post = Post.new
+ @post.category = "othervalue"
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"\"></option>\n<option value=\"othervalue\" selected=\"selected\">othervalue</option></select>",
+ select("post", "category", [nil, "othervalue"])
+ )
+ end
+
+ def test_select_with_fixnum
+ @post = Post.new
+ @post.category = ""
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"\"></option>\n<option value=\"1\">1</option></select>",
+ select("post", "category", [1], :prompt => true, :include_blank => true)
+ )
+ end
+
+ def test_list_of_lists
+ @post = Post.new
+ @post.category = ""
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"\"></option>\n<option value=\"number\">Number</option>\n<option value=\"text\">Text</option>\n<option value=\"boolean\">Yes/No</option></select>",
+ select("post", "category", [["Number", "number"], ["Text", "text"], ["Yes/No", "boolean"]], :prompt => true, :include_blank => true)
+ )
+ end
+
def test_select_with_selected_value
@post = Post.new
@post.category = "<mus>"
diff --git a/actionpack/test/template/form_tag_helper_test.rb b/actionpack/test/template/form_tag_helper_test.rb
index 6eae9bf846..233907d07a 100644
--- a/actionpack/test/template/form_tag_helper_test.rb
+++ b/actionpack/test/template/form_tag_helper_test.rb
@@ -2,6 +2,8 @@ require 'abstract_unit'
require 'active_support/core_ext/object/inclusion'
class FormTagHelperTest < ActionView::TestCase
+ include RenderERBUtils
+
tests ActionView::Helpers::FormTagHelper
def setup
@@ -104,14 +106,14 @@ class FormTagHelperTest < ActionView::TestCase
end
def test_form_tag_with_block_in_erb
- output_buffer = form_tag("http://www.example.com") { concat "Hello world!" }
+ output_buffer = render_erb("<%= form_tag('http://www.example.com') do %>Hello world!<% end %>")
expected = whole_form { "Hello world!" }
assert_dom_equal expected, output_buffer
end
def test_form_tag_with_block_and_method_in_erb
- output_buffer = form_tag("http://www.example.com", :method => :put) { concat "Hello world!" }
+ output_buffer = render_erb("<%= form_tag('http://www.example.com', :method => :put) do %>Hello world!<% end %>")
expected = whole_form("http://www.example.com", :method => "put") do
"Hello world!"
@@ -485,27 +487,27 @@ class FormTagHelperTest < ActionView::TestCase
end
def test_field_set_tag_in_erb
- output_buffer = field_set_tag("Your details") { concat "Hello world!" }
+ output_buffer = render_erb("<%= field_set_tag('Your details') do %>Hello world!<% end %>")
expected = %(<fieldset><legend>Your details</legend>Hello world!</fieldset>)
assert_dom_equal expected, output_buffer
- output_buffer = field_set_tag { concat "Hello world!" }
+ output_buffer = render_erb("<%= field_set_tag do %>Hello world!<% end %>")
expected = %(<fieldset>Hello world!</fieldset>)
assert_dom_equal expected, output_buffer
- output_buffer = field_set_tag('') { concat "Hello world!" }
+ output_buffer = render_erb("<%= field_set_tag('') do %>Hello world!<% end %>")
expected = %(<fieldset>Hello world!</fieldset>)
assert_dom_equal expected, output_buffer
- output_buffer = field_set_tag('', :class => 'format') { concat "Hello world!" }
+ output_buffer = render_erb("<%= field_set_tag('', :class => 'format') do %>Hello world!<% end %>")
expected = %(<fieldset class="format">Hello world!</fieldset>)
assert_dom_equal expected, output_buffer
end
-
+
def test_text_area_tag_options_symbolize_keys_side_effects
options = { :option => "random_option" }
text_area_tag "body", "hello world", options
diff --git a/actionpack/test/template/html-scanner/tag_node_test.rb b/actionpack/test/template/html-scanner/tag_node_test.rb
index 0d87f1bd42..3b72243e7d 100644
--- a/actionpack/test/template/html-scanner/tag_node_test.rb
+++ b/actionpack/test/template/html-scanner/tag_node_test.rb
@@ -55,7 +55,12 @@ class TagNodeTest < Test::Unit::TestCase
def test_to_s
node = tag("<a b=c d='f' g=\"h 'i'\" />")
- assert_equal %(<a b="c" d="f" g="h 'i'" />), node.to_s
+ node = node.to_s
+ assert node.include?('a')
+ assert node.include?('b="c"')
+ assert node.include?('d="f"')
+ assert node.include?('g="h')
+ assert node.include?('i')
end
def test_tag
diff --git a/actionpack/test/template/javascript_helper_test.rb b/actionpack/test/template/javascript_helper_test.rb
index 4b9c3c97b1..d98ffe8fa7 100644
--- a/actionpack/test/template/javascript_helper_test.rb
+++ b/actionpack/test/template/javascript_helper_test.rb
@@ -28,11 +28,7 @@ class JavaScriptHelperTest < ActionView::TestCase
assert_equal %(This \\"thing\\" is really\\n netos\\'), escape_javascript(%(This "thing" is really\n netos'))
assert_equal %(backslash\\\\test), escape_javascript( %(backslash\\test) )
assert_equal %(dont <\\/close> tags), escape_javascript(%(dont </close> tags))
- if "ruby".encoding_aware?
- assert_equal %(unicode &#x2028; newline), escape_javascript(%(unicode \342\200\250 newline).force_encoding('UTF-8').encode!)
- else
- assert_equal %(unicode &#x2028; newline), escape_javascript(%(unicode \342\200\250 newline))
- end
+ assert_equal %(unicode &#x2028; newline), escape_javascript(%(unicode \342\200\250 newline).force_encoding('UTF-8').encode!)
assert_equal %(dont <\\/close> tags), j(%(dont </close> tags))
end
diff --git a/actionpack/test/template/lookup_context_test.rb b/actionpack/test/template/lookup_context_test.rb
index bac2530e3d..c65f707da0 100644
--- a/actionpack/test/template/lookup_context_test.rb
+++ b/actionpack/test/template/lookup_context_test.rb
@@ -1,20 +1,14 @@
require "abstract_unit"
require "abstract_controller/rendering"
-ActionView::LookupContext::DetailsKey.class_eval do
- def self.details_keys
- @details_keys
- end
-end
-
class LookupContextTest < ActiveSupport::TestCase
def setup
@lookup_context = ActionView::LookupContext.new(FIXTURE_LOAD_PATH, {})
+ ActionView::LookupContext::DetailsKey.clear
end
def teardown
I18n.locale = :en
- ActionView::LookupContext::DetailsKey.details_keys.clear
end
test "process view paths on initialization" do
diff --git a/actionpack/test/template/number_helper_test.rb b/actionpack/test/template/number_helper_test.rb
index 0e3475d98b..8d679aac1d 100644
--- a/actionpack/test/template/number_helper_test.rb
+++ b/actionpack/test/template/number_helper_test.rb
@@ -27,6 +27,7 @@ class NumberHelperTest < ActionView::TestCase
assert_equal("800 555 1212", number_to_phone(8005551212, {:delimiter => " "}))
assert_equal("(800) 555-1212 x 123", number_to_phone(8005551212, {:area_code => true, :extension => 123}))
assert_equal("800-555-1212", number_to_phone(8005551212, :extension => " "))
+ assert_equal("555.1212", number_to_phone(5551212, :delimiter => '.'))
assert_equal("800-555-1212", number_to_phone("8005551212"))
assert_equal("+1-800-555-1212", number_to_phone(8005551212, :country_code => 1))
assert_equal("+18005551212", number_to_phone(8005551212, :country_code => 1, :delimiter => ''))
diff --git a/actionpack/test/template/output_buffer_test.rb b/actionpack/test/template/output_buffer_test.rb
index bd49a11af1..eb0df3d1ab 100644
--- a/actionpack/test/template/output_buffer_test.rb
+++ b/actionpack/test/template/output_buffer_test.rb
@@ -39,15 +39,13 @@ class OutputBufferTest < ActionController::TestCase
assert_equal ['foo', 'bar'], body_parts
end
- if '1.9'.respond_to?(:force_encoding)
- test 'flushing preserves output buffer encoding' do
- original_buffer = ' '.force_encoding(Encoding::EUC_JP)
- @vc.output_buffer = original_buffer
- @vc.flush_output_buffer
- assert_equal ['foo', original_buffer], body_parts
- assert_not_equal original_buffer, output_buffer
- assert_equal Encoding::EUC_JP, output_buffer.encoding
- end
+ test 'flushing preserves output buffer encoding' do
+ original_buffer = ' '.force_encoding(Encoding::EUC_JP)
+ @vc.output_buffer = original_buffer
+ @vc.flush_output_buffer
+ assert_equal ['foo', original_buffer], body_parts
+ assert_not_equal original_buffer, output_buffer
+ assert_equal Encoding::EUC_JP, output_buffer.encoding
end
protected
diff --git a/actionpack/test/template/output_safety_helper_test.rb b/actionpack/test/template/output_safety_helper_test.rb
index fc127c24e9..76c71c9e6d 100644
--- a/actionpack/test/template/output_safety_helper_test.rb
+++ b/actionpack/test/template/output_safety_helper_test.rb
@@ -1,9 +1,7 @@
require 'abstract_unit'
-require 'testing_sandbox'
class OutputSafetyHelperTest < ActionView::TestCase
tests ActionView::Helpers::OutputSafetyHelper
- include TestingSandbox
def setup
@string = "hello"
diff --git a/actionpack/test/template/record_tag_helper_test.rb b/actionpack/test/template/record_tag_helper_test.rb
index 7f23629e05..ec777d15c4 100644
--- a/actionpack/test/template/record_tag_helper_test.rb
+++ b/actionpack/test/template/record_tag_helper_test.rb
@@ -22,6 +22,8 @@ class Post
end
class RecordTagHelperTest < ActionView::TestCase
+ include RenderERBUtils
+
tests ActionView::Helpers::RecordTagHelper
def setup
@@ -58,13 +60,13 @@ class RecordTagHelperTest < ActionView::TestCase
def test_block_works_with_content_tag_for_in_erb
expected = %(<tr class="post" id="post_45">#{@post.body}</tr>)
- actual = content_tag_for(:tr, @post) { concat @post.body }
+ actual = render_erb("<%= content_tag_for(:tr, @post) do %><%= @post.body %><% end %>")
assert_dom_equal expected, actual
end
def test_div_for_in_erb
expected = %(<div class="post bar" id="post_45">#{@post.body}</div>)
- actual = div_for(@post, :class => "bar") { concat @post.body }
+ actual = render_erb("<%= div_for(@post, :class => 'bar') do %><%= @post.body %><% end %>")
assert_dom_equal expected, actual
end
diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb
index 0ef3239f83..5d3dc73ed2 100644
--- a/actionpack/test/template/render_test.rb
+++ b/actionpack/test/template/render_test.rb
@@ -20,6 +20,13 @@ module RenderTestCases
assert_equal ORIGINAL_LOCALES, I18n.available_locales.map {|l| l.to_s }.sort
end
+ def test_render_without_options
+ @view.render()
+ flunk "Render did not raise ArgumentError"
+ rescue ArgumentError => e
+ assert_match "You invoked render but did not give any of :partial, :template, :inline, :file or :text option.", e.message
+ end
+
def test_render_file
assert_equal "Hello world!", @view.render(:file => "test/hello_world")
end
@@ -43,21 +50,21 @@ module RenderTestCases
assert_match "<h1>No Comment</h1>", @view.render(:template => "comments/empty", :formats => [:html])
assert_match "<error>No Comment</error>", @view.render(:template => "comments/empty", :formats => [:xml])
end
-
+
def test_render_file_with_locale
assert_equal "<h1>Kein Kommentar</h1>", @view.render(:file => "comments/empty", :locale => [:de])
assert_equal "<h1>Kein Kommentar</h1>", @view.render(:file => "comments/empty", :locale => :de)
end
-
+
def test_render_template_with_locale
assert_equal "<h1>Kein Kommentar</h1>", @view.render(:template => "comments/empty", :locale => [:de])
end
-
+
def test_render_file_with_handlers
assert_equal "<h1>No Comment</h1>\n", @view.render(:file => "comments/empty", :handlers => [:builder])
assert_equal "<h1>No Comment</h1>\n", @view.render(:file => "comments/empty", :handlers => :builder)
end
-
+
def test_render_template_with_handlers
assert_equal "<h1>No Comment</h1>\n", @view.render(:template => "comments/empty", :handlers => [:builder])
end
@@ -142,6 +149,13 @@ module RenderTestCases
"and is followed by any combinations of letters, numbers, or underscores.", e.message
end
+ def test_render_partial_with_incompatible_object
+ @view.render(:partial => nil)
+ flunk "Render did not raise ArgumentError"
+ rescue ArgumentError => e
+ assert_equal "'#{nil.inspect}' is not an ActiveModel-compatible object. It must implement :to_partial_path.", e.message
+ end
+
def test_render_partial_with_errors
@view.render(:partial => "test/raise")
flunk "Render did not raise Template::Error"
@@ -236,36 +250,6 @@ module RenderTestCases
@controller_view.render(customers, :greeting => "Hello")
end
- class CustomerWithDeprecatedPartialPath
- attr_reader :name
-
- def self.model_name
- Struct.new(:partial_path).new("customers/customer")
- end
-
- def initialize(name)
- @name = name
- end
- end
-
- def test_render_partial_using_object_with_deprecated_partial_path
- assert_deprecated(/#model_name.*#partial_path.*#to_partial_path/) do
- assert_equal "Hello: nertzy",
- @controller_view.render(CustomerWithDeprecatedPartialPath.new("nertzy"), :greeting => "Hello")
- end
- end
-
- def test_render_partial_using_collection_with_deprecated_partial_path
- assert_deprecated(/#model_name.*#partial_path.*#to_partial_path/) do
- customers = [
- CustomerWithDeprecatedPartialPath.new("nertzy"),
- CustomerWithDeprecatedPartialPath.new("peeja")
- ]
- assert_equal "Hello: nertzyHello: peeja",
- @controller_view.render(customers, :greeting => "Hello")
- end
- end
-
# TODO: The reason for this test is unclear, improve documentation
def test_render_partial_and_fallback_to_layout
assert_equal "Before (Josh)\n\nAfter", @view.render(:partial => "test/layout_for_partial", :locals => { :name => "Josh" })
@@ -426,51 +410,49 @@ class LazyViewRenderTest < ActiveSupport::TestCase
GC.start
end
- if '1.9'.respond_to?(:force_encoding)
- def test_render_utf8_template_with_magic_comment
- with_external_encoding Encoding::ASCII_8BIT do
- result = @view.render(:file => "test/utf8_magic.html", :layouts => "layouts/yield")
- assert_equal Encoding::UTF_8, result.encoding
- assert_equal "\nРусский \nтекст\n\nUTF-8\nUTF-8\nUTF-8\n", result
- end
+ def test_render_utf8_template_with_magic_comment
+ with_external_encoding Encoding::ASCII_8BIT do
+ result = @view.render(:file => "test/utf8_magic", :formats => [:html], :layouts => "layouts/yield")
+ assert_equal Encoding::UTF_8, result.encoding
+ assert_equal "\nРусский \nтекст\n\nUTF-8\nUTF-8\nUTF-8\n", result
end
+ end
- def test_render_utf8_template_with_default_external_encoding
- with_external_encoding Encoding::UTF_8 do
- result = @view.render(:file => "test/utf8.html", :layouts => "layouts/yield")
- assert_equal Encoding::UTF_8, result.encoding
- assert_equal "Русский текст\n\nUTF-8\nUTF-8\nUTF-8\n", result
- end
+ def test_render_utf8_template_with_default_external_encoding
+ with_external_encoding Encoding::UTF_8 do
+ result = @view.render(:file => "test/utf8", :formats => [:html], :layouts => "layouts/yield")
+ assert_equal Encoding::UTF_8, result.encoding
+ assert_equal "Русский текст\n\nUTF-8\nUTF-8\nUTF-8\n", result
end
+ end
- def test_render_utf8_template_with_incompatible_external_encoding
- with_external_encoding Encoding::SHIFT_JIS do
- begin
- @view.render(:file => "test/utf8.html", :layouts => "layouts/yield")
- flunk 'Should have raised incompatible encoding error'
- rescue ActionView::Template::Error => error
- assert_match 'Your template was not saved as valid Shift_JIS', error.original_exception.message
- end
+ def test_render_utf8_template_with_incompatible_external_encoding
+ with_external_encoding Encoding::SHIFT_JIS do
+ begin
+ @view.render(:file => "test/utf8", :formats => [:html], :layouts => "layouts/yield")
+ flunk 'Should have raised incompatible encoding error'
+ rescue ActionView::Template::Error => error
+ assert_match 'Your template was not saved as valid Shift_JIS', error.original_exception.message
end
end
+ end
- def test_render_utf8_template_with_partial_with_incompatible_encoding
- with_external_encoding Encoding::SHIFT_JIS do
- begin
- @view.render(:file => "test/utf8_magic_with_bare_partial.html", :layouts => "layouts/yield")
- flunk 'Should have raised incompatible encoding error'
- rescue ActionView::Template::Error => error
- assert_match 'Your template was not saved as valid Shift_JIS', error.original_exception.message
- end
+ def test_render_utf8_template_with_partial_with_incompatible_encoding
+ with_external_encoding Encoding::SHIFT_JIS do
+ begin
+ @view.render(:file => "test/utf8_magic_with_bare_partial", :formats => [:html], :layouts => "layouts/yield")
+ flunk 'Should have raised incompatible encoding error'
+ rescue ActionView::Template::Error => error
+ assert_match 'Your template was not saved as valid Shift_JIS', error.original_exception.message
end
end
+ end
- def with_external_encoding(encoding)
- old = Encoding.default_external
- silence_warnings { Encoding.default_external = encoding }
- yield
- ensure
- silence_warnings { Encoding.default_external = old }
- end
+ def with_external_encoding(encoding)
+ old = Encoding.default_external
+ silence_warnings { Encoding.default_external = encoding }
+ yield
+ ensure
+ silence_warnings { Encoding.default_external = old }
end
end
diff --git a/actionpack/test/template/sanitize_helper_test.rb b/actionpack/test/template/sanitize_helper_test.rb
index 222d4dbf4c..4182af590e 100644
--- a/actionpack/test/template/sanitize_helper_test.rb
+++ b/actionpack/test/template/sanitize_helper_test.rb
@@ -1,11 +1,9 @@
require 'abstract_unit'
-require 'testing_sandbox'
# The exhaustive tests are in test/controller/html/sanitizer_test.rb.
# This tests the that the helpers hook up correctly to the sanitizer classes.
class SanitizeHelperTest < ActionView::TestCase
tests ActionView::Helpers::SanitizeHelper
- include TestingSandbox
def test_strip_links
assert_equal "Dont touch me", strip_links("Dont touch me")
diff --git a/actionpack/test/template/sprockets_helper_test.rb b/actionpack/test/template/sprockets_helper_test.rb
index 08b66fec8b..64fdd53e73 100644
--- a/actionpack/test/template/sprockets_helper_test.rb
+++ b/actionpack/test/template/sprockets_helper_test.rb
@@ -41,6 +41,10 @@ class SprocketsHelperTest < ActionView::TestCase
@controller ? @controller.config : @config
end
+ def compute_host(source, request, options = {})
+ raise "Should never get here"
+ end
+
test "asset_path" do
assert_match %r{/assets/logo-[0-9a-f]+.png},
asset_path("logo.png")
@@ -125,6 +129,10 @@ class SprocketsHelperTest < ActionView::TestCase
assert_raises ActionController::RoutingError do
asset_path("logo.png")
end
+ @config.asset_host = method :compute_host
+ assert_raises ActionController::RoutingError do
+ asset_path("logo.png")
+ end
end
test "image_tag" do
@@ -217,8 +225,13 @@ class SprocketsHelperTest < ActionView::TestCase
assert_match %r{<script src="/assets/xmlhr-[0-9a-f]+.js\?body=1" type="text/javascript"></script>\n<script src="/assets/application-[0-9a-f]+.js\?body=1" type="text/javascript"></script>},
javascript_include_tag(:application, :debug => true)
+ assert_match %r{<script src="/assets/jquery.plugin.js" type="text/javascript"></script>},
+ javascript_include_tag('jquery.plugin', :digest => false)
+
@config.assets.compile = true
@config.assets.debug = true
+ assert_match %r{<script src="/javascripts/application.js" type="text/javascript"></script>},
+ javascript_include_tag('/javascripts/application')
assert_match %r{<script src="/assets/xmlhr-[0-9a-f]+.js\?body=1" type="text/javascript"></script>\n<script src="/assets/application-[0-9a-f]+.js\?body=1" type="text/javascript"></script>},
javascript_include_tag(:application)
end
@@ -264,6 +277,9 @@ class SprocketsHelperTest < ActionView::TestCase
@config.assets.compile = true
@config.assets.debug = true
+ assert_match %r{<link href="/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />},
+ stylesheet_link_tag('/stylesheets/application')
+
assert_match %r{<link href="/assets/style-[0-9a-f]+.css\?body=1" media="screen" rel="stylesheet" type="text/css" />\n<link href="/assets/application-[0-9a-f]+.css\?body=1" media="screen" rel="stylesheet" type="text/css" />},
stylesheet_link_tag(:application)
diff --git a/actionpack/test/template/sprockets_helper_with_routes_test.rb b/actionpack/test/template/sprockets_helper_with_routes_test.rb
new file mode 100644
index 0000000000..bcbd81a7dd
--- /dev/null
+++ b/actionpack/test/template/sprockets_helper_with_routes_test.rb
@@ -0,0 +1,57 @@
+require 'abstract_unit'
+require 'sprockets'
+require 'sprockets/helpers/rails_helper'
+require 'mocha'
+
+class SprocketsHelperWithRoutesTest < ActionView::TestCase
+ include Sprockets::Helpers::RailsHelper
+
+ # Let's bring in some named routes to test namespace conflicts with potential *_paths.
+ # We have to do this after we bring in the Sprockets RailsHelper so if there are conflicts,
+ # they'll fail in the way we expect in a real live Rails app.
+ routes = ActionDispatch::Routing::RouteSet.new
+ routes.draw do
+ resources :assets
+ end
+ include routes.url_helpers
+
+ def setup
+ super
+ @controller = BasicController.new
+
+ @assets = Sprockets::Environment.new
+ @assets.append_path(FIXTURES.join("sprockets/app/javascripts"))
+ @assets.append_path(FIXTURES.join("sprockets/app/stylesheets"))
+ @assets.append_path(FIXTURES.join("sprockets/app/images"))
+
+ application = Struct.new(:config, :assets).new(config, @assets)
+ Rails.stubs(:application).returns(application)
+ @config = config
+ @config.perform_caching = true
+ @config.assets.digest = true
+ @config.assets.compile = true
+ end
+
+ test "namespace conflicts on a named route called asset_path" do
+ # Testing this for sanity - asset_path is now a named route!
+ assert_match asset_path('test_asset'), '/assets/test_asset'
+
+ assert_match %r{/assets/logo-[0-9a-f]+.png},
+ path_to_asset("logo.png")
+ assert_match %r{/assets/logo-[0-9a-f]+.png},
+ path_to_asset("logo.png", :digest => true)
+ assert_match %r{/assets/logo.png},
+ path_to_asset("logo.png", :digest => false)
+ end
+
+ test "javascript_include_tag with a named_route named asset_path" do
+ assert_match %r{<script src="/assets/application-[0-9a-f]+.js" type="text/javascript"></script>},
+ javascript_include_tag(:application)
+ end
+
+ test "stylesheet_link_tag with a named_route named asset_path" do
+ assert_match %r{<link href="/assets/application-[0-9a-f]+.css" media="screen" rel="stylesheet" type="text/css" />},
+ stylesheet_link_tag(:application)
+ end
+
+end \ No newline at end of file
diff --git a/actionpack/test/template/tag_helper_test.rb b/actionpack/test/template/tag_helper_test.rb
index 60b466a9ff..6c325d5abb 100644
--- a/actionpack/test/template/tag_helper_test.rb
+++ b/actionpack/test/template/tag_helper_test.rb
@@ -1,6 +1,8 @@
require 'abstract_unit'
class TagHelperTest < ActionView::TestCase
+ include RenderERBUtils
+
tests ActionView::Helpers::TagHelper
def test_tag
@@ -44,12 +46,12 @@ class TagHelperTest < ActionView::TestCase
end
def test_content_tag_with_block_in_erb
- buffer = content_tag(:div) { concat "Hello world!" }
+ buffer = render_erb("<%= content_tag(:div) do %>Hello world!<% end %>")
assert_dom_equal "<div>Hello world!</div>", buffer
end
def test_content_tag_with_block_and_options_in_erb
- buffer = content_tag(:div, :class => "green") { concat "Hello world!" }
+ buffer = render_erb("<%= content_tag(:div, :class => 'green') do %>Hello world!<% end %>")
assert_dom_equal %(<div class="green">Hello world!</div>), buffer
end
@@ -68,10 +70,8 @@ class TagHelperTest < ActionView::TestCase
output_buffer
end
- # TAG TODO: Move this into a real template
def test_content_tag_nested_in_content_tag_in_erb
- buffer = content_tag("p") { concat content_tag("b", "Hello") }
- assert_equal '<p><b>Hello</b></p>', buffer
+ assert_equal "<p>\n <b>Hello</b>\n</p>", view.render("test/content_tag_nested_in_content_tag")
end
def test_content_tag_with_escaped_array_class
diff --git a/actionpack/test/template/template_test.rb b/actionpack/test/template/template_test.rb
index b0ca7de0b6..f9c228f0c3 100644
--- a/actionpack/test/template/template_test.rb
+++ b/actionpack/test/template/template_test.rb
@@ -8,6 +8,9 @@ class TestERBTemplate < ActiveSupport::TestCase
def disable_cache
yield
end
+
+ def find_template(*args)
+ end
end
class Context
@@ -111,66 +114,65 @@ class TestERBTemplate < ActiveSupport::TestCase
end
end
- if "ruby".encoding_aware?
- def test_resulting_string_is_utf8
- @template = new_template
- assert_equal Encoding::UTF_8, render.encoding
- end
+ def test_resulting_string_is_utf8
+ @template = new_template
+ assert_equal Encoding::UTF_8, render.encoding
+ end
- def test_no_magic_comment_word_with_utf_8
- @template = new_template("hello \u{fc}mlat")
+ def test_no_magic_comment_word_with_utf_8
+ @template = new_template("hello \u{fc}mlat")
+ assert_equal Encoding::UTF_8, render.encoding
+ assert_equal "hello \u{fc}mlat", render
+ end
+
+ # This test ensures that if the default_external
+ # is set to something other than UTF-8, we don't
+ # get any errors and get back a UTF-8 String.
+ def test_default_external_works
+ with_external_encoding "ISO-8859-1" do
+ @template = new_template("hello \xFCmlat")
assert_equal Encoding::UTF_8, render.encoding
assert_equal "hello \u{fc}mlat", render
end
+ end
- # This test ensures that if the default_external
- # is set to something other than UTF-8, we don't
- # get any errors and get back a UTF-8 String.
- def test_default_external_works
- with_external_encoding "ISO-8859-1" do
- @template = new_template("hello \xFCmlat")
- assert_equal Encoding::UTF_8, render.encoding
- assert_equal "hello \u{fc}mlat", render
- end
- end
-
- def test_encoding_can_be_specified_with_magic_comment
- @template = new_template("# encoding: ISO-8859-1\nhello \xFCmlat")
- assert_equal Encoding::UTF_8, render.encoding
- assert_equal "\nhello \u{fc}mlat", render
- end
+ def test_encoding_can_be_specified_with_magic_comment
+ @template = new_template("# encoding: ISO-8859-1\nhello \xFCmlat")
+ assert_equal Encoding::UTF_8, render.encoding
+ assert_equal "\nhello \u{fc}mlat", render
+ end
- # TODO: This is currently handled inside ERB. The case of explicitly
- # lying about encodings via the normal Rails API should be handled
- # inside Rails.
- def test_lying_with_magic_comment
- assert_raises(ActionView::Template::Error) do
- @template = new_template("# encoding: UTF-8\nhello \xFCmlat", :virtual_path => nil)
- render
- end
+ # TODO: This is currently handled inside ERB. The case of explicitly
+ # lying about encodings via the normal Rails API should be handled
+ # inside Rails.
+ def test_lying_with_magic_comment
+ assert_raises(ActionView::Template::Error) do
+ @template = new_template("# encoding: UTF-8\nhello \xFCmlat", :virtual_path => nil)
+ render
end
+ end
- def test_encoding_can_be_specified_with_magic_comment_in_erb
- with_external_encoding Encoding::UTF_8 do
- @template = new_template("<%# encoding: ISO-8859-1 %>hello \xFCmlat", :virtual_path => nil)
- assert_equal Encoding::UTF_8, render.encoding
- assert_equal "hello \u{fc}mlat", render
- end
+ def test_encoding_can_be_specified_with_magic_comment_in_erb
+ with_external_encoding Encoding::UTF_8 do
+ @template = new_template("<%# encoding: ISO-8859-1 %>hello \xFCmlat", :virtual_path => nil)
+ assert_equal Encoding::UTF_8, render.encoding
+ assert_equal "hello \u{fc}mlat", render
end
+ end
- def test_error_when_template_isnt_valid_utf8
- assert_raises(ActionView::Template::Error, /\xFC/) do
- @template = new_template("hello \xFCmlat", :virtual_path => nil)
- render
- end
+ def test_error_when_template_isnt_valid_utf8
+ assert_raises(ActionView::Template::Error, /\xFC/) do
+ @template = new_template("hello \xFCmlat", :virtual_path => nil)
+ render
end
+ end
- def with_external_encoding(encoding)
- old = Encoding.default_external
- silence_warnings { Encoding.default_external = encoding }
- yield
- ensure
- silence_warnings { Encoding.default_external = old }
- end
+ def with_external_encoding(encoding)
+ old = Encoding.default_external
+ Encoding::Converter.new old, encoding if old != encoding
+ silence_warnings { Encoding.default_external = encoding }
+ yield
+ ensure
+ silence_warnings { Encoding.default_external = old }
end
end
diff --git a/actionpack/test/template/test_test.rb b/actionpack/test/template/test_test.rb
index bf789cd8b7..adcbf1447f 100644
--- a/actionpack/test/template/test_test.rb
+++ b/actionpack/test/template/test_test.rb
@@ -62,3 +62,19 @@ class CrazyHelperTest < ActionView::TestCase
assert_equal PeopleHelper, self.class.helper_class
end
end
+
+class CrazySymbolHelperTest < ActionView::TestCase
+ tests :people
+
+ def test_set_helper_class_using_symbol
+ assert_equal PeopleHelper, self.class.helper_class
+ end
+end
+
+class CrazyStringHelperTest < ActionView::TestCase
+ tests 'people'
+
+ def test_set_helper_class_using_string
+ assert_equal PeopleHelper, self.class.helper_class
+ end
+end
diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb
index 02f9609483..839bf900dc 100644
--- a/actionpack/test/template/text_helper_test.rb
+++ b/actionpack/test/template/text_helper_test.rb
@@ -1,10 +1,8 @@
# encoding: utf-8
require 'abstract_unit'
-require 'testing_sandbox'
class TextHelperTest < ActionView::TestCase
tests ActionView::Helpers::TextHelper
- include TestingSandbox
def setup
super
@@ -82,25 +80,13 @@ class TextHelperTest < ActionView::TestCase
assert_equal "Hello Big[...]", truncate("Hello Big World!", :omission => "[...]", :length => 15, :separator => ' ')
end
- if RUBY_VERSION < '1.9.0'
- def test_truncate_multibyte
- with_kcode 'none' do
- assert_equal "\354\225\210\353\205\225\355...", truncate("\354\225\210\353\205\225\355\225\230\354\204\270\354\232\224", :length => 10)
- end
- with_kcode 'u' do
- assert_equal "\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 ...",
- truncate("\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 \354\225\204\353\235\274\353\246\254\354\230\244", :length => 10)
- end
- end
- else
- def test_truncate_multibyte
- # .mb_chars always returns a UTF-8 String.
- # assert_equal "\354\225\210\353\205\225\355...",
- # truncate("\354\225\210\353\205\225\355\225\230\354\204\270\354\232\224", :length => 10)
+ def test_truncate_multibyte
+ # .mb_chars always returns a UTF-8 String.
+ # assert_equal "\354\225\210\353\205\225\355...",
+ # truncate("\354\225\210\353\205\225\355\225\230\354\204\270\354\232\224", :length => 10)
- assert_equal "\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 ...".force_encoding('UTF-8'),
- truncate("\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 \354\225\204\353\235\274\353\246\254\354\230\244".force_encoding('UTF-8'), :length => 10)
- end
+ assert_equal "\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 ...".force_encoding('UTF-8'),
+ truncate("\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 \354\225\204\353\235\274\353\246\254\354\230\244".force_encoding('UTF-8'), :length => 10)
end
def test_highlight_should_be_html_safe
@@ -194,6 +180,10 @@ class TextHelperTest < ActionView::TestCase
"<p>This is a <strong class=\"highlight\">beautiful</strong> <a href=\"http://example.com/beautiful#top?what=beautiful%20morning&amp;when=now+then\">morning</a>, but also a <strong class=\"highlight\">beautiful</strong> day</p>",
highlight("<p>This is a beautiful <a href=\"http://example.com/beautiful\#top?what=beautiful%20morning&when=now+then\">morning</a>, but also a beautiful day</p>", "beautiful")
)
+ assert_equal(
+ "<div>abc <b>div</b></div>",
+ highlight("<div>abc div</div>", "div", :highlighter => '<b>\1</b>')
+ )
end
def test_excerpt
@@ -239,21 +229,10 @@ class TextHelperTest < ActionView::TestCase
)
end
- if RUBY_VERSION < '1.9'
- def test_excerpt_with_utf8
- with_kcode('u') do
- assert_equal("...\357\254\203ciency could not be...", excerpt("That's why e\357\254\203ciency could not be helped", 'could', 8))
- end
- with_kcode('none') do
- assert_equal("...\203ciency could not be...", excerpt("That's why e\357\254\203ciency could not be helped", 'could', 8))
- end
- end
- else
- def test_excerpt_with_utf8
- assert_equal("...\357\254\203ciency could not be...".force_encoding('UTF-8'), excerpt("That's why e\357\254\203ciency could not be helped".force_encoding('UTF-8'), 'could', 8))
- # .mb_chars always returns UTF-8, even in 1.9. This is not great, but it's how it works. Let's work this out.
- # assert_equal("...\203ciency could not be...", excerpt("That's why e\357\254\203ciency could not be helped".force_encoding("BINARY"), 'could', 8))
- end
+ def test_excerpt_with_utf8
+ assert_equal("...\357\254\203ciency could not be...".force_encoding('UTF-8'), excerpt("That's why e\357\254\203ciency could not be helped".force_encoding('UTF-8'), 'could', 8))
+ # .mb_chars always returns UTF-8, even in 1.9. This is not great, but it's how it works. Let's work this out.
+ # assert_equal("...\203ciency could not be...", excerpt("That's why e\357\254\203ciency could not be helped".force_encoding("BINARY"), 'could', 8))
end
def test_word_wrap
diff --git a/actionpack/test/template/translation_helper_test.rb b/actionpack/test/template/translation_helper_test.rb
index cd9f54e04c..397de9c2ce 100644
--- a/actionpack/test/template/translation_helper_test.rb
+++ b/actionpack/test/template/translation_helper_test.rb
@@ -17,8 +17,13 @@ class TranslationHelperTest < ActiveSupport::TestCase
:hello => '<a>Hello World</a>',
:html => '<a>Hello World</a>',
:hello_html => '<a>Hello World</a>',
+ :interpolated_html => '<a>Hello %{word}</a>',
:array_html => %w(foo bar),
- :array => %w(foo bar)
+ :array => %w(foo bar),
+ :count_html => {
+ :one => '<a>One %{count}</a>',
+ :other => '<a>Other %{count}</a>'
+ }
}
)
@view = ::ActionView::Base.new(ActionController::Base.view_paths, {})
@@ -83,6 +88,17 @@ class TranslationHelperTest < ActiveSupport::TestCase
assert translate(:'translations.hello_html').html_safe?
end
+ def test_translate_escapes_interpolations_in_translations_with_a_html_suffix
+ assert_equal '<a>Hello &lt;World&gt;</a>', translate(:'translations.interpolated_html', :word => '<World>')
+ assert_equal '<a>Hello &lt;World&gt;</a>', translate(:'translations.interpolated_html', :word => stub(:to_s => "<World>"))
+ end
+
+ def test_translate_with_html_count
+ assert_equal '<a>One 1</a>', translate(:'translations.count_html', :count => 1)
+ assert_equal '<a>Other 2</a>', translate(:'translations.count_html', :count => 2)
+ assert_equal '<a>Other &lt;One&gt;</a>', translate(:'translations.count_html', :count => '<One>')
+ end
+
def test_translation_returning_an_array_ignores_html_suffix
assert_equal ["foo", "bar"], translate(:'translations.array_html')
end