aboutsummaryrefslogtreecommitdiffstats
path: root/actionpack/test
diff options
context:
space:
mode:
Diffstat (limited to 'actionpack/test')
-rw-r--r--actionpack/test/abstract_controller/abstract_controller_test.rb57
-rw-r--r--actionpack/test/abstract_controller/callbacks_test.rb39
-rw-r--r--actionpack/test/abstract_controller/helper_test.rb6
-rw-r--r--actionpack/test/abstract_controller/layouts_test.rb31
-rw-r--r--actionpack/test/abstract_controller/test_helper.rb12
-rw-r--r--actionpack/test/abstract_unit.rb8
-rw-r--r--actionpack/test/activerecord/active_record_store_test.rb29
-rw-r--r--actionpack/test/activerecord/polymorphic_routes_test.rb1
-rw-r--r--actionpack/test/adv_attr_test.rb20
-rw-r--r--actionpack/test/controller/action_pack_assertions_test.rb79
-rw-r--r--actionpack/test/controller/addresses_render_test.rb1
-rw-r--r--actionpack/test/controller/base_test.rb12
-rw-r--r--actionpack/test/controller/caching_test.rb44
-rw-r--r--actionpack/test/controller/capture_test.rb1
-rw-r--r--actionpack/test/controller/content_type_test.rb13
-rw-r--r--actionpack/test/controller/cookie_test.rb47
-rw-r--r--actionpack/test/controller/deprecation/deprecated_base_methods_test.rb6
-rw-r--r--actionpack/test/controller/dispatcher_test.rb47
-rw-r--r--actionpack/test/controller/filter_params_test.rb45
-rw-r--r--actionpack/test/controller/filters_test.rb251
-rw-r--r--actionpack/test/controller/flash_test.rb71
-rw-r--r--actionpack/test/controller/helper_test.rb44
-rw-r--r--actionpack/test/controller/http_digest_authentication_test.rb36
-rw-r--r--actionpack/test/controller/integration_test.rb45
-rw-r--r--actionpack/test/controller/layout_test.rb64
-rw-r--r--actionpack/test/controller/logging_test.rb9
-rw-r--r--actionpack/test/controller/mime_responds_test.rb48
-rw-r--r--actionpack/test/controller/redirect_test.rb5
-rw-r--r--actionpack/test/controller/render_js_test.rb39
-rw-r--r--actionpack/test/controller/render_json_test.rb80
-rw-r--r--actionpack/test/controller/render_other_test.rb238
-rw-r--r--actionpack/test/controller/render_test.rb422
-rw-r--r--actionpack/test/controller/render_xml_test.rb81
-rw-r--r--actionpack/test/controller/request/test_request_test.rb23
-rw-r--r--actionpack/test/controller/rescue_test.rb360
-rw-r--r--actionpack/test/controller/resources_test.rb8
-rw-r--r--actionpack/test/controller/routing_test.rb14
-rw-r--r--actionpack/test/controller/selector_test.rb1
-rw-r--r--actionpack/test/controller/send_file_test.rb41
-rw-r--r--actionpack/test/controller/test_test.rb41
-rw-r--r--actionpack/test/controller/verification_test.rb16
-rw-r--r--actionpack/test/controller/view_paths_test.rb51
-rw-r--r--actionpack/test/controller/webservice_test.rb4
-rw-r--r--actionpack/test/dispatch/rack_test.rb90
-rw-r--r--actionpack/test/dispatch/request/multipart_params_parsing_test.rb64
-rw-r--r--actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb38
-rw-r--r--actionpack/test/dispatch/request_test.rb2
-rw-r--r--actionpack/test/dispatch/response_test.rb130
-rw-r--r--actionpack/test/dispatch/session/cookie_store_test.rb6
-rw-r--r--actionpack/test/dispatch/session/mem_cache_store_test.rb8
-rw-r--r--actionpack/test/dispatch/session/test_session_test.rb24
-rw-r--r--actionpack/test/dispatch/show_exceptions_test.rb108
-rw-r--r--actionpack/test/dispatch/test_request_test.rb45
-rw-r--r--actionpack/test/fixtures/layout_tests/layouts/third_party_template_library.mab2
-rw-r--r--actionpack/test/fixtures/layouts/standard.html.erb (renamed from actionpack/test/fixtures/layouts/standard.erb)0
-rw-r--r--actionpack/test/fixtures/test/greeting.html.erb (renamed from actionpack/test/fixtures/test/greeting.erb)0
-rw-r--r--actionpack/test/fixtures/test/render_file_with_locals_and_default.erb1
-rw-r--r--actionpack/test/fixtures/test/utf8.html.erb5
-rw-r--r--actionpack/test/html-scanner/cdata_node_test.rb (renamed from actionpack/test/controller/html-scanner/cdata_node_test.rb)0
-rw-r--r--actionpack/test/html-scanner/document_test.rb (renamed from actionpack/test/controller/html-scanner/document_test.rb)0
-rw-r--r--actionpack/test/html-scanner/node_test.rb (renamed from actionpack/test/controller/html-scanner/node_test.rb)0
-rw-r--r--actionpack/test/html-scanner/sanitizer_test.rb (renamed from actionpack/test/controller/html-scanner/sanitizer_test.rb)0
-rw-r--r--actionpack/test/html-scanner/tag_node_test.rb (renamed from actionpack/test/controller/html-scanner/tag_node_test.rb)0
-rw-r--r--actionpack/test/html-scanner/text_node_test.rb (renamed from actionpack/test/controller/html-scanner/text_node_test.rb)0
-rw-r--r--actionpack/test/html-scanner/tokenizer_test.rb (renamed from actionpack/test/controller/html-scanner/tokenizer_test.rb)0
-rw-r--r--actionpack/test/lib/active_record_unit.rb (renamed from actionpack/test/active_record_unit.rb)6
-rw-r--r--actionpack/test/lib/controller/fake_controllers.rb (renamed from actionpack/test/controller/fake_controllers.rb)0
-rw-r--r--actionpack/test/lib/controller/fake_models.rb (renamed from actionpack/test/controller/fake_models.rb)0
-rw-r--r--actionpack/test/lib/fixture_template.rb115
-rw-r--r--actionpack/test/lib/testing_sandbox.rb (renamed from actionpack/test/testing_sandbox.rb)0
-rw-r--r--actionpack/test/new_base/abstract_unit.rb166
-rw-r--r--actionpack/test/new_base/base_test.rb103
-rw-r--r--actionpack/test/new_base/content_type_test.rb111
-rw-r--r--actionpack/test/new_base/etag_test.rb46
-rw-r--r--actionpack/test/new_base/redirect_test.rb1
-rw-r--r--actionpack/test/new_base/render_action_test.rb417
-rw-r--r--actionpack/test/new_base/render_file_test.rb110
-rw-r--r--actionpack/test/new_base/render_implicit_action_test.rb30
-rw-r--r--actionpack/test/new_base/render_layout_test.rb106
-rw-r--r--actionpack/test/new_base/render_partial_test.rb27
-rw-r--r--actionpack/test/new_base/render_template_test.rb211
-rw-r--r--actionpack/test/new_base/render_test.rb85
-rw-r--r--actionpack/test/new_base/render_text_test.rb197
-rw-r--r--actionpack/test/new_base/render_xml_test.rb11
-rw-r--r--actionpack/test/new_base/test_helper.rb126
-rw-r--r--actionpack/test/template/body_parts_test.rb11
-rw-r--r--actionpack/test/template/compiled_templates_test.rb36
-rw-r--r--actionpack/test/template/form_options_helper_test.rb22
-rw-r--r--actionpack/test/template/javascript_helper_test.rb4
-rw-r--r--actionpack/test/template/number_helper_test.rb4
-rw-r--r--actionpack/test/template/output_buffer_test.rb67
-rw-r--r--actionpack/test/template/prototype_helper_test.rb20
-rw-r--r--actionpack/test/template/render_test.rb36
-rw-r--r--actionpack/test/template/text_helper_test.rb10
94 files changed, 3062 insertions, 2029 deletions
diff --git a/actionpack/test/abstract_controller/abstract_controller_test.rb b/actionpack/test/abstract_controller/abstract_controller_test.rb
index 918062c7db..9c028e7d1e 100644
--- a/actionpack/test/abstract_controller/abstract_controller_test.rb
+++ b/actionpack/test/abstract_controller/abstract_controller_test.rb
@@ -20,14 +20,14 @@ module AbstractController
class TestBasic < ActiveSupport::TestCase
test "dispatching works" do
result = Me.process(:index)
- assert_equal "Hello world", result.response_obj[:body]
+ assert_equal "Hello world", result.response_body
end
end
# Test Render mixin
# ====
class RenderingController < AbstractController::Base
- use Renderer
+ include Renderer
def _prefix() end
@@ -58,38 +58,38 @@ module AbstractController
end
def rendering_to_body
- render_to_body "naked_render.erb"
+ self.response_body = render_to_body :_template_name => "naked_render.erb"
end
def rendering_to_string
- render_to_string "naked_render.erb"
+ self.response_body = render_to_string :_template_name => "naked_render.erb"
end
end
class TestRenderer < ActiveSupport::TestCase
test "rendering templates works" do
result = Me2.process(:index)
- assert_equal "Hello from index.erb", result.response_obj[:body]
+ assert_equal "Hello from index.erb", result.response_body
end
test "rendering passes ivars to the view" do
result = Me2.process(:action_with_ivars)
- assert_equal "Hello from index_with_ivars.erb", result.response_obj[:body]
+ assert_equal "Hello from index_with_ivars.erb", result.response_body
end
test "rendering with no template name" do
result = Me2.process(:naked_render)
- assert_equal "Hello from naked_render.erb", result.response_obj[:body]
+ assert_equal "Hello from naked_render.erb", result.response_body
end
test "rendering to a rack body" do
result = Me2.process(:rendering_to_body)
- assert_equal "Hello from naked_render.erb", result.response_obj[:body]
+ assert_equal "Hello from naked_render.erb", result.response_body
end
test "rendering to a string" do
result = Me2.process(:rendering_to_string)
- assert_equal "Hello from naked_render.erb", result.response_obj[:body]
+ assert_equal "Hello from naked_render.erb", result.response_body
end
end
@@ -121,12 +121,12 @@ module AbstractController
class TestPrefixedViews < ActiveSupport::TestCase
test "templates are located inside their 'prefix' folder" do
result = Me3.process(:index)
- assert_equal "Hello from me3/index.erb", result.response_obj[:body]
+ assert_equal "Hello from me3/index.erb", result.response_body
end
test "templates included their format" do
result = Me3.process(:formatted)
- assert_equal "Hello from me3/formatted.html.erb", result.response_obj[:body]
+ assert_equal "Hello from me3/formatted.html.erb", result.response_body
end
end
@@ -134,26 +134,27 @@ module AbstractController
# ====
# self._layout is used when defined
class WithLayouts < PrefixedViews
- use Layouts
+ include Layouts
+
+ def self.inherited(klass)
+ klass._write_layout_method
+ super
+ end
private
def self.layout(formats)
begin
- view_paths.find_by_parts(name.underscore, formats, "layouts")
+ view_paths.find_by_parts(name.underscore, {:formats => formats}, "layouts")
rescue ActionView::MissingTemplate
begin
- view_paths.find_by_parts("application", formats, "layouts")
+ view_paths.find_by_parts("application", {:formats => formats}, "layouts")
rescue ActionView::MissingTemplate
end
end
end
-
- def _layout
- self.class.layout(formats)
- end
-
+
def render_to_body(options = {})
- options[:_layout] = options[:layout] || _layout
+ options[:_layout] = options[:layout] || _default_layout
super
end
end
@@ -173,12 +174,7 @@ module AbstractController
class TestLayouts < ActiveSupport::TestCase
test "layouts are included" do
result = Me4.process(:index)
- assert_equal "Me4 Enter : Hello from me4/index.erb : Exit", result.response_obj[:body]
- end
-
- test "it can fall back to the application layout" do
- result = Me5.process(:index)
- assert_equal "Application Enter : Hello from me5/index.erb : Exit", result.response_obj[:body]
+ assert_equal "Me4 Enter : Hello from me4/index.erb : Exit", result.response_body
end
end
@@ -205,17 +201,16 @@ module AbstractController
def fail() self.response_body = "fail" end
private
-
- def respond_to_action?(action_name)
- action_name != :fail
+
+ def method_for_action(action_name)
+ action_name.to_s != "fail" && action_name
end
-
end
class TestRespondToAction < ActiveSupport::TestCase
def assert_dispatch(klass, body = "success", action = :index)
- response = klass.process(action).response_obj[:body]
+ response = klass.process(action).response_body
assert_equal body, response
end
diff --git a/actionpack/test/abstract_controller/callbacks_test.rb b/actionpack/test/abstract_controller/callbacks_test.rb
index 5fce30f478..1de60868c3 100644
--- a/actionpack/test/abstract_controller/callbacks_test.rb
+++ b/actionpack/test/abstract_controller/callbacks_test.rb
@@ -4,7 +4,7 @@ module AbstractController
module Testing
class ControllerWithCallbacks < AbstractController::Base
- use AbstractController::Callbacks
+ include AbstractController::Callbacks
end
class Callback1 < ControllerWithCallbacks
@@ -22,7 +22,7 @@ module AbstractController
class TestCallbacks < ActiveSupport::TestCase
test "basic callbacks work" do
result = Callback1.process(:index)
- assert_equal "Hello world", result.response_obj[:body]
+ assert_equal "Hello world", result.response_body
end
end
@@ -53,7 +53,7 @@ module AbstractController
class TestCallbacks < ActiveSupport::TestCase
test "before_filter works" do
result = Callback2.process(:index)
- assert_equal "Hello world", result.response_obj[:body]
+ assert_equal "Hello world", result.response_body
end
test "after_filter works" do
@@ -84,7 +84,7 @@ module AbstractController
class TestCallbacks < ActiveSupport::TestCase
test "before_filter works with procs" do
result = Callback3.process(:index)
- assert_equal "Hello world", result.response_obj[:body]
+ assert_equal "Hello world", result.response_body
end
test "after_filter works with procs" do
@@ -119,12 +119,12 @@ module AbstractController
class TestCallbacks < ActiveSupport::TestCase
test "when :only is specified, a before filter is triggered on that action" do
result = CallbacksWithConditions.process(:index)
- assert_equal "Hello, World", result.response_obj[:body]
+ assert_equal "Hello, World", result.response_body
end
test "when :only is specified, a before filter is not triggered on other actions" do
result = CallbacksWithConditions.process(:sekrit_data)
- assert_equal "true", result.response_obj[:body]
+ assert_equal "true", result.response_body
end
test "when :except is specified, an after filter is not triggered on that action" do
@@ -159,12 +159,12 @@ module AbstractController
class TestCallbacks < ActiveSupport::TestCase
test "when :only is specified with an array, a before filter is triggered on that action" do
result = CallbacksWithArrayConditions.process(:index)
- assert_equal "Hello, World", result.response_obj[:body]
+ assert_equal "Hello, World", result.response_body
end
test "when :only is specified with an array, a before filter is not triggered on other actions" do
result = CallbacksWithArrayConditions.process(:sekrit_data)
- assert_equal "true", result.response_obj[:body]
+ assert_equal "true", result.response_body
end
test "when :except is specified with an array, an after filter is not triggered on that action" do
@@ -184,12 +184,31 @@ module AbstractController
class TestCallbacks < ActiveSupport::TestCase
test "when a callback is modified in a child with :only, it works for the :only action" do
result = ChangedConditions.process(:index)
- assert_equal "Hello world", result.response_obj[:body]
+ assert_equal "Hello world", result.response_body
end
test "when a callback is modified in a child with :only, it does not work for other actions" do
result = ChangedConditions.process(:not_index)
- assert_equal "", result.response_obj[:body]
+ assert_equal "", result.response_body
+ end
+ end
+
+ class SetsResponseBody < ControllerWithCallbacks
+ before_filter :set_body
+
+ def index
+ self.response_body = "Fail"
+ end
+
+ def set_body
+ self.response_body = "Success"
+ end
+ end
+
+ class TestHalting < ActiveSupport::TestCase
+ test "when a callback sets the response body, the action should not be invoked" do
+ result = SetsResponseBody.process(:index)
+ assert_equal "Success", result.response_body
end
end
diff --git a/actionpack/test/abstract_controller/helper_test.rb b/actionpack/test/abstract_controller/helper_test.rb
index 6284fa4f70..f91aefe606 100644
--- a/actionpack/test/abstract_controller/helper_test.rb
+++ b/actionpack/test/abstract_controller/helper_test.rb
@@ -4,8 +4,8 @@ module AbstractController
module Testing
class ControllerWithHelpers < AbstractController::Base
- use Renderer
- use Helpers
+ include Renderer
+ include Helpers
def render(string)
super(:_template_name => string)
@@ -35,7 +35,7 @@ module AbstractController
class TestHelpers < ActiveSupport::TestCase
def test_helpers
result = MyHelpers1.process(:index)
- assert_equal "Hello World : Included", result.response_obj[:body]
+ assert_equal "Hello World : Included", result.response_body
end
end
diff --git a/actionpack/test/abstract_controller/layouts_test.rb b/actionpack/test/abstract_controller/layouts_test.rb
index 3d4570bfef..d3440c3de0 100644
--- a/actionpack/test/abstract_controller/layouts_test.rb
+++ b/actionpack/test/abstract_controller/layouts_test.rb
@@ -1,14 +1,15 @@
require File.join(File.expand_path(File.dirname(__FILE__)), "test_helper")
+require 'active_support/core_ext/class/removal'
module AbstractControllerTests
module Layouts
# Base controller for these tests
class Base < AbstractController::Base
- use AbstractController::Renderer
- use AbstractController::Layouts
-
- self.view_paths = [ActionView::FixtureTemplate::FixturePath.new(
+ include AbstractController::Renderer
+ include AbstractController::Layouts
+
+ self.view_paths = [ActionView::Template::FixturePath.new(
"layouts/hello.erb" => "With String <%= yield %>",
"layouts/hello_override.erb" => "With Override <%= yield %>",
"layouts/abstract_controller_tests/layouts/with_string_implied_child.erb" =>
@@ -152,12 +153,12 @@ module AbstractControllerTests
class TestBase < ActiveSupport::TestCase
test "when no layout is specified, and no default is available, render without a layout" do
result = Blank.process(:index)
- assert_equal "Hello blank!", result.response_obj[:body]
+ assert_equal "Hello blank!", result.response_body
end
test "when layout is specified as a string, render with that layout" do
result = WithString.process(:index)
- assert_equal "With String Hello string!", result.response_obj[:body]
+ assert_equal "With String Hello string!", result.response_body
end
test "when layout is specified as a string, but the layout is missing, raise an exception" do
@@ -166,22 +167,22 @@ module AbstractControllerTests
test "when layout is specified as false, do not use a layout" do
result = WithFalseLayout.process(:index)
- assert_equal "Hello false!", result.response_obj[:body]
+ assert_equal "Hello false!", result.response_body
end
test "when layout is specified as nil, do not use a layout" do
result = WithNilLayout.process(:index)
- assert_equal "Hello nil!", result.response_obj[:body]
+ assert_equal "Hello nil!", result.response_body
end
test "when layout is specified as a symbol, call the requested method and use the layout returned" do
result = WithSymbol.process(:index)
- assert_equal "OMGHI2U Hello symbol!", result.response_obj[:body]
+ assert_equal "OMGHI2U Hello symbol!", result.response_body
end
test "when layout is specified as a symbol and the method returns nil, don't use a layout" do
result = WithSymbolReturningNil.process(:index)
- assert_equal "Hello nilz!", result.response_obj[:body]
+ assert_equal "Hello nilz!", result.response_body
end
test "when the layout is specified as a symbol and the method doesn't exist, raise an exception" do
@@ -194,28 +195,28 @@ module AbstractControllerTests
test "when a child controller does not have a layout, use the parent controller layout" do
result = WithStringChild.process(:index)
- assert_equal "With String Hello string!", result.response_obj[:body]
+ assert_equal "With String Hello string!", result.response_body
end
test "when a child controller has specified a layout, use that layout and not the parent controller layout" do
result = WithStringOverriddenChild.process(:index)
- assert_equal "With Override Hello string!", result.response_obj[:body]
+ assert_equal "With Override Hello string!", result.response_body
end
test "when a child controller has an implied layout, use that layout and not the parent controller layout" do
result = WithStringImpliedChild.process(:index)
- assert_equal "With Implied Hello string!", result.response_obj[:body]
+ assert_equal "With Implied Hello string!", result.response_body
end
test "when a child controller specifies layout nil, do not use the parent layout" do
result = WithNilChild.process(:index)
- assert_equal "Hello string!", result.response_obj[:body]
+ assert_equal "Hello string!", result.response_body
end
test "when a grandchild has no layout specified, the child has an implied layout, and the " \
"parent has specified a layout, use the child controller layout" do
result = WithChildOfImplied.process(:index)
- assert_equal "With Implied Hello string!", result.response_obj[:body]
+ assert_equal "With Implied Hello string!", result.response_body
end
test "raises an exception when specifying layout true" do
diff --git a/actionpack/test/abstract_controller/test_helper.rb b/actionpack/test/abstract_controller/test_helper.rb
index b9248c6bbd..915054f7fb 100644
--- a/actionpack/test/abstract_controller/test_helper.rb
+++ b/actionpack/test/abstract_controller/test_helper.rb
@@ -2,11 +2,14 @@ $:.unshift(File.dirname(__FILE__) + '/../../lib')
$:.unshift(File.dirname(__FILE__) + '/../../../activesupport/lib')
$:.unshift(File.dirname(__FILE__) + '/../lib')
+require 'rubygems'
require 'test/unit'
require 'active_support'
require 'active_support/test_case'
-require 'action_controller'
+require 'action_controller/abstract'
+require 'action_view'
require 'action_view/base'
+require 'action_dispatch'
require 'fixture_template'
begin
@@ -16,10 +19,3 @@ begin
rescue LoadError
# Debugging disabled. `gem install ruby-debug` to enable.
end
-
-require 'action_controller/abstract'
-# require 'action_controller/abstract/base'
-# require 'action_controller/abstract/renderer'
-# require 'action_controller/abstract/layouts'
-# require 'action_controller/abstract/callbacks'
-# require 'action_controller/abstract/helpers' \ No newline at end of file
diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb
index b07e6e5f3a..c71da7fa6c 100644
--- a/actionpack/test/abstract_unit.rb
+++ b/actionpack/test/abstract_unit.rb
@@ -1,3 +1,7 @@
+if ENV['new_base']
+ puts *caller
+ raise 'new_base/abstract_unit already loaded'
+end
$:.unshift(File.dirname(__FILE__) + '/../lib')
$:.unshift(File.dirname(__FILE__) + '/../../activesupport/lib')
$:.unshift(File.dirname(__FILE__) + '/fixtures/helpers')
@@ -23,6 +27,8 @@ require 'action_controller'
require 'action_controller/testing/process'
require 'action_view/test_case'
+$tags[:old_base] = true
+
# Show backtraces for deprecated behavior for quicker cleanup.
ActiveSupport::Deprecation.debug = true
@@ -34,7 +40,7 @@ ActionController::Base.session_store = nil
# Register danish language for testing
I18n.backend.store_translations 'da', {}
I18n.backend.store_translations 'pt-BR', {}
-ORIGINAL_LOCALES = I18n.available_locales.map(&:to_s).sort
+ORIGINAL_LOCALES = I18n.available_locales.map {|locale| locale.to_s }.sort
FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures')
ActionController::Base.view_paths = FIXTURE_LOAD_PATH
diff --git a/actionpack/test/activerecord/active_record_store_test.rb b/actionpack/test/activerecord/active_record_store_test.rb
index 34f18806a2..9ac33b3417 100644
--- a/actionpack/test/activerecord/active_record_store_test.rb
+++ b/actionpack/test/activerecord/active_record_store_test.rb
@@ -13,6 +13,7 @@ class ActiveRecordStoreTest < ActionController::IntegrationTest
end
def set_session_value
+ raise "missing session!" unless session
session[:foo] = params[:foo] || "bar"
head :ok
end
@@ -21,15 +22,20 @@ class ActiveRecordStoreTest < ActionController::IntegrationTest
render :text => "foo: #{session[:foo].inspect}"
end
+ def set_cookie_and_get_session_value
+ cookies["kittens"] = { :value => "fluffy" }
+ render :text => "foo: #{session[:foo].inspect}"
+ end
+
def get_session_id
session[:foo]
render :text => "#{request.session_options[:id]}"
end
def call_reset_session
- session[:bar]
+ session[:foo]
reset_session
- session[:bar] = "baz"
+ session[:foo] = "baz"
head :ok
end
@@ -77,6 +83,23 @@ class ActiveRecordStoreTest < ActionController::IntegrationTest
end
end
+ def test_getting_session_value_does_not_set_cookie
+ with_test_route_set do
+ get '/get_session_value'
+ assert_response :success
+ assert_equal "", headers["Set-Cookie"]
+ end
+ end
+
+ def test_getting_session_value_and_setting_a_cookie_doesnt_delete_all_cookies
+ with_test_route_set do
+ get '/set_cookie_and_get_session_value'
+ assert_response :success
+ assert_equal 'foo: nil', response.body
+ assert_equal({"kittens" => "fluffy"}, response.cookies)
+ end
+ end
+
def test_setting_session_value_after_session_reset
with_test_route_set do
get '/set_session_value'
@@ -90,7 +113,7 @@ class ActiveRecordStoreTest < ActionController::IntegrationTest
get '/get_session_value'
assert_response :success
- assert_equal 'foo: nil', response.body
+ assert_equal 'foo: "baz"', response.body
get '/get_session_id'
assert_response :success
diff --git a/actionpack/test/activerecord/polymorphic_routes_test.rb b/actionpack/test/activerecord/polymorphic_routes_test.rb
index 35139fbb7f..b9f5be2361 100644
--- a/actionpack/test/activerecord/polymorphic_routes_test.rb
+++ b/actionpack/test/activerecord/polymorphic_routes_test.rb
@@ -1,4 +1,5 @@
require 'active_record_unit'
+require 'fixtures/project'
class Task < ActiveRecord::Base
set_table_name 'projects'
diff --git a/actionpack/test/adv_attr_test.rb b/actionpack/test/adv_attr_test.rb
deleted file mode 100644
index fdda4ad92d..0000000000
--- a/actionpack/test/adv_attr_test.rb
+++ /dev/null
@@ -1,20 +0,0 @@
-require File.dirname(__FILE__) + '/abstract_unit'
-require 'action_mailer/adv_attr_accessor'
-
-class AdvAttrTest < Test::Unit::TestCase
- class Person
- include ActionMailer::AdvAttrAccessor
- adv_attr_accessor :name
- end
-
- def test_adv_attr
- bob = Person.new
- assert_nil bob.name
- bob.name 'Bob'
- assert_equal 'Bob', bob.name
-
- assert_raise(ArgumentError) {bob.name 'x', 'y'}
- end
-
-
-end \ No newline at end of file
diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb
index 96f7a42c9b..24686ab4b6 100644
--- a/actionpack/test/controller/action_pack_assertions_test.rb
+++ b/actionpack/test/controller/action_pack_assertions_test.rb
@@ -1,4 +1,5 @@
require 'abstract_unit'
+require 'action_controller/vendor/html-scanner'
# a controller class to facilitate the tests
class ActionPackAssertionsController < ActionController::Base
@@ -12,6 +13,9 @@ class ActionPackAssertionsController < ActionController::Base
# a standard template
def hello_xml_world() render :template => "test/hello_xml_world"; end
+ # a standard partial
+ def partial() render :partial => 'test/partial'; end
+
# a redirect to an internal location
def redirect_internal() redirect_to "/nothing"; end
@@ -292,47 +296,73 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
# make sure that the template objects exist
def test_template_objects_alive
process :assign_this
- assert !@response.has_template_object?('hi')
- assert @response.has_template_object?('howdy')
+ assert !@controller.template.instance_variable_get(:"@hi")
+ assert @controller.template.instance_variable_get(:"@howdy")
end
# make sure we don't have template objects when we shouldn't
def test_template_object_missing
process :nothing
- assert_nil @response.template_objects['howdy']
+ assert_nil @controller.template.assigns['howdy']
end
# check the empty flashing
def test_flash_me_naked
process :flash_me_naked
- assert !@response.has_flash?
- assert !@response.has_flash_with_contents?
+ assert_deprecated do
+ assert !@response.has_flash?
+ assert !@response.has_flash_with_contents?
+ end
end
# check if we have flash objects
def test_flash_haves
process :flash_me
- assert @response.has_flash?
- assert @response.has_flash_with_contents?
- assert @response.has_flash_object?('hello')
+ assert_deprecated do
+ assert @response.has_flash?
+ assert @response.has_flash_with_contents?
+ assert @response.has_flash_object?('hello')
+ end
end
# ensure we don't have flash objects
def test_flash_have_nots
process :nothing
- assert !@response.has_flash?
- assert !@response.has_flash_with_contents?
- assert_nil @response.flash['hello']
+ assert_deprecated do
+ assert !@response.has_flash?
+ assert !@response.has_flash_with_contents?
+ assert_nil @response.flash['hello']
+ end
+ end
+
+ def test_assert_template_with_partial
+ get :partial
+ assert_template :partial => '_partial'
+ end
+
+ def test_assert_template_with_nil
+ get :nothing
+ assert_template nil
+ end
+
+ def test_assert_template_with_string
+ get :hello_world
+ assert_template 'hello_world'
+ end
+
+ def test_assert_template_with_symbol
+ get :hello_world
+ assert_template :hello_world
end
# check if we were rendered by a file-based template?
def test_rendered_action
process :nothing
- assert_nil @response.rendered[:template]
+ assert_nil @controller.template.rendered[:template]
process :hello_world
- assert @response.rendered[:template]
- assert 'hello_world', @response.rendered[:template].to_s
+ assert @controller.template.rendered[:template]
+ assert 'hello_world', @controller.template.rendered[:template].to_s
end
# check the redirection location
@@ -378,10 +408,12 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
def test_redirect_url_match
process :redirect_external
assert @response.redirect?
- assert @response.redirect_url_match?("rubyonrails")
- assert @response.redirect_url_match?(/rubyonrails/)
- assert !@response.redirect_url_match?("phpoffrails")
- assert !@response.redirect_url_match?(/perloffrails/)
+ assert_deprecated do
+ assert @response.redirect_url_match?("rubyonrails")
+ assert @response.redirect_url_match?(/rubyonrails/)
+ assert !@response.redirect_url_match?("phpoffrails")
+ assert !@response.redirect_url_match?(/perloffrails/)
+ end
end
# check for a redirection
@@ -413,7 +445,6 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
assert_equal "Mr. David", @response.body
end
-
def test_assert_redirection_fails_with_incorrect_controller
process :redirect_to_controller
assert_raise(ActiveSupport::TestCase::Assertion) do
@@ -481,7 +512,7 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
get :index
assert_response :success
flunk 'Expected non-success response'
- rescue ActiveSupport::TestCase::Assertion => e
+ rescue RuntimeError => e
assert e.message.include?('FAIL')
end
@@ -506,9 +537,11 @@ class ActionPackHeaderTest < ActionController::TestCase
end
def test_rendering_xml_respects_content_type
- @response.headers['type'] = 'application/pdf'
- process :hello_xml_world
- assert_equal('application/pdf; charset=utf-8', @response.headers['Content-Type'])
+ pending do
+ @response.headers['type'] = 'application/pdf'
+ process :hello_xml_world
+ assert_equal('application/pdf; charset=utf-8', @response.headers['Content-Type'])
+ end
end
def test_render_text_with_custom_content_type
diff --git a/actionpack/test/controller/addresses_render_test.rb b/actionpack/test/controller/addresses_render_test.rb
index 2f092b6731..2d2a2745b0 100644
--- a/actionpack/test/controller/addresses_render_test.rb
+++ b/actionpack/test/controller/addresses_render_test.rb
@@ -1,4 +1,5 @@
require 'abstract_unit'
+require 'logger'
class Address
def Address.count(conditions = nil, join = nil)
diff --git a/actionpack/test/controller/base_test.rb b/actionpack/test/controller/base_test.rb
index f4517d06c4..3a4cdb81d9 100644
--- a/actionpack/test/controller/base_test.rb
+++ b/actionpack/test/controller/base_test.rb
@@ -1,4 +1,5 @@
require 'abstract_unit'
+require '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.
@@ -27,6 +28,7 @@ class EmptyController < ActionController::Base
end
class NonEmptyController < ActionController::Base
def public_action
+ render :nothing => true
end
hide_action :hidden_action
@@ -51,6 +53,7 @@ end
class DefaultUrlOptionsController < ActionController::Base
def default_url_options_action
+ render :nothing => true
end
def default_url_options(options = nil)
@@ -114,7 +117,7 @@ class PerformActionTest < ActionController::TestCase
end
def method_missing(method, *args)
- @logged << args.first
+ @logged << args.first.to_s
end
end
@@ -151,11 +154,8 @@ class PerformActionTest < ActionController::TestCase
def test_get_on_hidden_should_fail
use_controller NonEmptyController
- get :hidden_action
- assert_response 404
-
- get :another_hidden_action
- assert_response 404
+ assert_raise(ActionController::UnknownAction) { get :hidden_action }
+ assert_raise(ActionController::UnknownAction) { get :another_hidden_action }
end
def test_namespaced_action_should_log_module_name
diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb
index b61a58dd09..c286976315 100644
--- a/actionpack/test/controller/caching_test.rb
+++ b/actionpack/test/controller/caching_test.rb
@@ -1,5 +1,6 @@
require 'fileutils'
require 'abstract_unit'
+require 'active_record_unit'
CACHE_DIR = 'test_cache'
# Don't change '/../temp/' cavalierly or you might hose something you don't want hosed
@@ -47,6 +48,8 @@ class PageCachingTest < ActionController::TestCase
super
ActionController::Base.perform_caching = true
+ ActionController::Routing::Routes.clear!
+
ActionController::Routing::Routes.draw do |map|
map.main '', :controller => 'posts'
map.formatted_posts 'posts.:format', :controller => 'posts'
@@ -110,7 +113,7 @@ class PageCachingTest < ActionController::TestCase
end
def test_should_cache_ok_at_custom_path
- @request.stubs(:path).returns("/index.html")
+ @request.request_uri = "/index.html"
get :ok
assert_response :ok
assert File.exist?("#{FILE_STORE_PATH}/index.html")
@@ -148,11 +151,15 @@ class PageCachingTest < ActionController::TestCase
end
class ActionCachingTestController < ActionController::Base
+ rescue_from(Exception) { head 500 }
+ rescue_from(ActiveRecord::RecordNotFound) { head :not_found }
+
caches_action :index, :redirected, :forbidden, :if => Proc.new { |c| !c.request.format.json? }, :expires_in => 1.hour
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 :layout_false, :layout => false
+ caches_action :record_not_found, :four_oh_four, :simple_runtime_error
layout 'talk_from_action.erb'
@@ -175,6 +182,18 @@ class ActionCachingTestController < ActionController::Base
render :text => @cache_this, :layout => true
end
+ def record_not_found
+ raise ActiveRecord::RecordNotFound, "oops!"
+ end
+
+ def four_oh_four
+ render :text => "404'd!", :status => 404
+ end
+
+ def simple_runtime_error
+ raise "oops!"
+ end
+
alias_method :show, :index
alias_method :edit, :index
alias_method :destroy, :index
@@ -345,7 +364,7 @@ class ActionCacheTest < ActionController::TestCase
cached_time = content_to_cache
reset!
- @request.set_REQUEST_URI "/action_caching_test/expire.xml"
+ @request.request_uri = "/action_caching_test/expire.xml"
get :expire, :format => :xml
reset!
@@ -458,6 +477,27 @@ class ActionCacheTest < ActionController::TestCase
assert_response :success
end
+ def test_record_not_found_returns_404_for_multiple_requests
+ get :record_not_found
+ assert_response 404
+ get :record_not_found
+ assert_response 404
+ end
+
+ def test_four_oh_four_returns_404_for_multiple_requests
+ get :four_oh_four
+ assert_response 404
+ get :four_oh_four
+ assert_response 404
+ end
+
+ def test_simple_runtime_error_returns_500_for_multiple_requests
+ get :simple_runtime_error
+ assert_response 500
+ get :simple_runtime_error
+ assert_response 500
+ end
+
private
def content_to_cache
assigns(:cache_this)
diff --git a/actionpack/test/controller/capture_test.rb b/actionpack/test/controller/capture_test.rb
index 9a0976ca9f..06a5af6b32 100644
--- a/actionpack/test/controller/capture_test.rb
+++ b/actionpack/test/controller/capture_test.rb
@@ -1,4 +1,5 @@
require 'abstract_unit'
+require 'logger'
class CaptureController < ActionController::Base
def self.controller_name; "test"; end
diff --git a/actionpack/test/controller/content_type_test.rb b/actionpack/test/controller/content_type_test.rb
index 7377546631..d622ac1e85 100644
--- a/actionpack/test/controller/content_type_test.rb
+++ b/actionpack/test/controller/content_type_test.rb
@@ -1,24 +1,29 @@
require 'abstract_unit'
class ContentTypeController < ActionController::Base
+ # :ported:
def render_content_type_from_body
response.content_type = Mime::RSS
render :text => "hello world!"
end
+ # :ported:
def render_defaults
render :text => "hello world!"
end
+ # :ported:
def render_content_type_from_render
render :text => "hello world!", :content_type => Mime::RSS
end
+ # :ported:
def render_charset_from_body
response.charset = "utf-16"
render :text => "hello world!"
end
+ # :ported:
def render_nil_charset_from_body
response.charset = nil
render :text => "hello world!"
@@ -60,6 +65,7 @@ class ContentTypeTest < ActionController::TestCase
@controller.logger = Logger.new(nil)
end
+ # :ported:
def test_render_defaults
get :render_defaults
assert_equal "utf-8", @response.charset
@@ -74,24 +80,28 @@ class ContentTypeTest < ActionController::TestCase
ContentTypeController.default_charset = "utf-8"
end
+ # :ported:
def test_content_type_from_body
get :render_content_type_from_body
assert_equal "application/rss+xml", @response.content_type
assert_equal "utf-8", @response.charset
end
+ # :ported:
def test_content_type_from_render
get :render_content_type_from_render
assert_equal "application/rss+xml", @response.content_type
assert_equal "utf-8", @response.charset
end
+ # :ported:
def test_charset_from_body
get :render_charset_from_body
assert_equal Mime::HTML, @response.content_type
assert_equal "utf-16", @response.charset
end
+ # :ported:
def test_nil_charset_from_body
get :render_nil_charset_from_body
assert_equal Mime::HTML, @response.content_type
@@ -138,12 +148,13 @@ class AcceptBasedContentTypeTest < ActionController::TestCase
def setup
super
+ @_old_accept_header = ActionController::Base.use_accept_header
ActionController::Base.use_accept_header = true
end
def teardown
super
- ActionController::Base.use_accept_header = false
+ ActionController::Base.use_accept_header = @_old_accept_header
end
diff --git a/actionpack/test/controller/cookie_test.rb b/actionpack/test/controller/cookie_test.rb
index c861982698..7199da3441 100644
--- a/actionpack/test/controller/cookie_test.rb
+++ b/actionpack/test/controller/cookie_test.rb
@@ -4,44 +4,48 @@ class CookieTest < ActionController::TestCase
class TestController < ActionController::Base
def authenticate
cookies["user_name"] = "david"
+ head :ok
end
def set_with_with_escapable_characters
cookies["that & guy"] = "foo & bar => baz"
+ head :ok
end
def authenticate_for_fourteen_days
cookies["user_name"] = { "value" => "david", "expires" => Time.utc(2005, 10, 10,5) }
+ head :ok
end
def authenticate_for_fourteen_days_with_symbols
cookies[:user_name] = { :value => "david", :expires => Time.utc(2005, 10, 10,5) }
+ head :ok
end
def set_multiple_cookies
cookies["user_name"] = { "value" => "david", "expires" => Time.utc(2005, 10, 10,5) }
cookies["login"] = "XJ-122"
+ head :ok
end
def access_frozen_cookies
cookies["will"] = "work"
+ head :ok
end
def logout
cookies.delete("user_name")
+ head :ok
end
def delete_cookie_with_path
cookies.delete("user_name", :path => '/beaten')
- render :text => "hello world"
+ head :ok
end
def authenticate_with_http_only
cookies["user_name"] = { :value => "david", :httponly => true }
- end
-
- def rescue_action(e)
- raise unless ActionView::MissingTemplate # No templates here, and we don't care about the output
+ head :ok
end
end
@@ -54,39 +58,38 @@ class CookieTest < ActionController::TestCase
def test_setting_cookie
get :authenticate
- assert_equal ["user_name=david; path=/"], @response.headers["Set-Cookie"]
+ assert_cookie_header "user_name=david; path=/"
assert_equal({"user_name" => "david"}, @response.cookies)
end
def test_setting_with_escapable_characters
get :set_with_with_escapable_characters
- assert_equal ["that+%26+guy=foo+%26+bar+%3D%3E+baz; path=/"], @response.headers["Set-Cookie"]
+ assert_cookie_header "that+%26+guy=foo+%26+bar+%3D%3E+baz; path=/"
assert_equal({"that & guy" => "foo & bar => baz"}, @response.cookies)
end
def test_setting_cookie_for_fourteen_days
get :authenticate_for_fourteen_days
- assert_equal ["user_name=david; path=/; expires=Mon, 10-Oct-2005 05:00:00 GMT"], @response.headers["Set-Cookie"]
+ assert_cookie_header "user_name=david; path=/; expires=Mon, 10-Oct-2005 05:00:00 GMT"
assert_equal({"user_name" => "david"}, @response.cookies)
end
def test_setting_cookie_for_fourteen_days_with_symbols
get :authenticate_for_fourteen_days_with_symbols
- assert_equal ["user_name=david; path=/; expires=Mon, 10-Oct-2005 05:00:00 GMT"], @response.headers["Set-Cookie"]
+ assert_cookie_header "user_name=david; path=/; expires=Mon, 10-Oct-2005 05:00:00 GMT"
assert_equal({"user_name" => "david"}, @response.cookies)
end
def test_setting_cookie_with_http_only
get :authenticate_with_http_only
- assert_equal ["user_name=david; path=/; HttpOnly"], @response.headers["Set-Cookie"]
+ assert_cookie_header "user_name=david; path=/; HttpOnly"
assert_equal({"user_name" => "david"}, @response.cookies)
end
def test_multiple_cookies
get :set_multiple_cookies
assert_equal 2, @response.cookies.size
- assert_equal "user_name=david; path=/; expires=Mon, 10-Oct-2005 05:00:00 GMT", @response.headers["Set-Cookie"][0]
- assert_equal "login=XJ-122; path=/", @response.headers["Set-Cookie"][1]
+ assert_cookie_header "user_name=david; path=/; expires=Mon, 10-Oct-2005 05:00:00 GMT\nlogin=XJ-122; path=/"
assert_equal({"login" => "XJ-122", "user_name" => "david"}, @response.cookies)
end
@@ -96,7 +99,7 @@ class CookieTest < ActionController::TestCase
def test_expiring_cookie
get :logout
- assert_equal ["user_name=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT"], @response.headers["Set-Cookie"]
+ assert_cookie_header "user_name=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT"
assert_equal({"user_name" => nil}, @response.cookies)
end
@@ -117,6 +120,22 @@ class CookieTest < ActionController::TestCase
def test_delete_cookie_with_path
get :delete_cookie_with_path
- assert_equal ["user_name=; path=/beaten; expires=Thu, 01-Jan-1970 00:00:00 GMT"], @response.headers["Set-Cookie"]
+ assert_cookie_header "user_name=; path=/beaten; expires=Thu, 01-Jan-1970 00:00:00 GMT"
+ end
+
+ def test_cookies_persist_throughout_request
+ get :authenticate
+ cookies = @controller.send(:cookies)
+ assert_equal 'david', cookies['user_name']
end
+
+ private
+ def assert_cookie_header(expected)
+ header = @response.headers["Set-Cookie"]
+ if header.respond_to?(:to_str)
+ assert_equal expected, header
+ else
+ assert_equal expected.split("\n"), header
+ end
+ end
end
diff --git a/actionpack/test/controller/deprecation/deprecated_base_methods_test.rb b/actionpack/test/controller/deprecation/deprecated_base_methods_test.rb
index dd69a63020..0c02afea36 100644
--- a/actionpack/test/controller/deprecation/deprecated_base_methods_test.rb
+++ b/actionpack/test/controller/deprecation/deprecated_base_methods_test.rb
@@ -15,12 +15,6 @@ class DeprecatedBaseMethodsTest < ActionController::TestCase
tests Target
- def test_log_error_silences_deprecation_warnings
- get :raises_name_error
- rescue => e
- assert_not_deprecated { @controller.send :log_error, e }
- end
-
if defined? Test::Unit::Error
def test_assertion_failed_error_silences_deprecation_warnings
get :raises_name_error
diff --git a/actionpack/test/controller/dispatcher_test.rb b/actionpack/test/controller/dispatcher_test.rb
index 569d698a03..9fae1fcf63 100644
--- a/actionpack/test/controller/dispatcher_test.rb
+++ b/actionpack/test/controller/dispatcher_test.rb
@@ -6,20 +6,20 @@ class DispatcherTest < Test::Unit::TestCase
def setup
ENV['REQUEST_METHOD'] = 'GET'
- Dispatcher.middleware = ActionDispatch::MiddlewareStack.new do |middleware|
- middlewares = File.expand_path(File.join(File.dirname(__FILE__), "../../lib/action_controller/dispatch/middlewares.rb"))
- middleware.instance_eval(File.read(middlewares))
- end
-
# Clear callbacks as they are redefined by Dispatcher#define_dispatcher_callbacks
- Dispatcher.instance_variable_set("@prepare_dispatch_callbacks", ActiveSupport::Callbacks::CallbackChain.new)
- Dispatcher.instance_variable_set("@before_dispatch_callbacks", ActiveSupport::Callbacks::CallbackChain.new)
- Dispatcher.instance_variable_set("@after_dispatch_callbacks", ActiveSupport::Callbacks::CallbackChain.new)
+ ActionDispatch::Callbacks.instance_variable_set("@prepare_callbacks", ActiveSupport::Callbacks::CallbackChain.new)
+ ActionDispatch::Callbacks.instance_variable_set("@before_callbacks", ActiveSupport::Callbacks::CallbackChain.new)
+ ActionDispatch::Callbacks.instance_variable_set("@after_callbacks", ActiveSupport::Callbacks::CallbackChain.new)
+ @old_router, Dispatcher.router = Dispatcher.router, mock()
+ Dispatcher.router.stubs(:call).returns([200, {}, 'response'])
+ Dispatcher.router.stubs(:reload)
Dispatcher.stubs(:require_dependency)
end
def teardown
+ Dispatcher.router = @old_router
+ @dispatcher = nil
ENV.delete 'REQUEST_METHOD'
end
@@ -29,12 +29,12 @@ class DispatcherTest < Test::Unit::TestCase
end
def test_reloads_routes_before_dispatch_if_in_loading_mode
- ActionController::Routing::Routes.expects(:reload).once
+ Dispatcher.router.expects(:reload).once
dispatch(false)
end
def test_leaves_dependencies_after_dispatch_if_not_in_loading_mode
- ActionController::Routing::Routes.expects(:reload).never
+ Dispatcher.router.expects(:reload).never
ActiveSupport::Dependencies.expects(:clear).never
dispatch
@@ -45,19 +45,6 @@ class DispatcherTest < Test::Unit::TestCase
def log_failsafe_exception(status, exception); end
end
- def test_failsafe_response
- Dispatcher.any_instance.expects(:_call).raises('b00m')
- ActionDispatch::Failsafe.any_instance.expects(:log_failsafe_exception)
-
- assert_nothing_raised do
- assert_equal [
- 500,
- {"Content-Type" => "text/html"},
- "<html><body><h1>500 Internal Server Error</h1></body></html>"
- ], dispatch
- end
- end
-
def test_prepare_callbacks
a = b = c = nil
Dispatcher.to_prepare { |*args| a = b = c = 1 }
@@ -68,7 +55,7 @@ class DispatcherTest < Test::Unit::TestCase
assert_nil a || b || c
# Run callbacks
- Dispatcher.run_prepare_callbacks
+ dispatch
assert_equal 1, a
assert_equal 2, b
@@ -85,16 +72,22 @@ class DispatcherTest < Test::Unit::TestCase
Dispatcher.to_prepare(:unique_id) { |*args| a = b = 1 }
Dispatcher.to_prepare(:unique_id) { |*args| a = 2 }
- Dispatcher.run_prepare_callbacks
+ dispatch
assert_equal 2, a
assert_equal nil, b
end
private
def dispatch(cache_classes = true)
- ActionController::Routing::RouteSet.any_instance.stubs(:call).returns([200, {}, 'response'])
+ ActionController::Dispatcher.prepare_each_request = false
Dispatcher.define_dispatcher_callbacks(cache_classes)
- Dispatcher.new.call({'rack.input' => StringIO.new('')})
+ Dispatcher.middleware = ActionDispatch::MiddlewareStack.new do |middleware|
+ middlewares = File.expand_path(File.join(File.dirname(__FILE__), "../../lib/action_controller/dispatch/middlewares.rb"))
+ middleware.instance_eval(File.read(middlewares))
+ end
+
+ @dispatcher ||= Dispatcher.new
+ @dispatcher.call({'rack.input' => StringIO.new(''), 'action_dispatch.show_exceptions' => false})
end
def assert_subclasses(howmany, klass, message = klass.subclasses.inspect)
diff --git a/actionpack/test/controller/filter_params_test.rb b/actionpack/test/controller/filter_params_test.rb
index 0b259a7980..8c9e4f81de 100644
--- a/actionpack/test/controller/filter_params_test.rb
+++ b/actionpack/test/controller/filter_params_test.rb
@@ -1,13 +1,30 @@
require 'abstract_unit'
class FilterParamController < ActionController::Base
+ def payment
+ head :ok
+ end
end
-class FilterParamTest < Test::Unit::TestCase
- def setup
- @controller = FilterParamController.new
+class FilterParamTest < ActionController::TestCase
+ tests FilterParamController
+
+ class MockLogger
+ attr_reader :logged
+ attr_accessor :level
+
+ def initialize
+ @level = Logger::DEBUG
+ end
+
+ def method_missing(method, *args)
+ @logged ||= []
+ @logged << args.first
+ end
end
+ setup :set_logger
+
def test_filter_parameters
assert FilterParamController.respond_to?(:filter_parameter_logging)
assert !@controller.respond_to?(:filter_parameters)
@@ -46,4 +63,26 @@ class FilterParamTest < Test::Unit::TestCase
assert !FilterParamController.action_methods.include?('filter_parameters')
assert_raise(NoMethodError) { @controller.filter_parameters([{'password' => '[FILTERED]'}]) }
end
+
+ def test_filter_parameters_inside_logs
+ FilterParamController.filter_parameter_logging(:lifo, :amount)
+
+ get :payment, :lifo => 'Pratik', :amount => '420', :step => '1'
+
+ filtered_params_logs = logs.detect {|l| l =~ /\AParameters/ }
+
+ assert filtered_params_logs.index('"amount"=>"[FILTERED]"')
+ assert filtered_params_logs.index('"lifo"=>"[FILTERED]"')
+ assert filtered_params_logs.index('"step"=>"1"')
+ end
+
+ private
+
+ def set_logger
+ @controller.logger = MockLogger.new
+ end
+
+ def logs
+ @logs ||= @controller.logger.logged.compact.map {|l| l.to_s.strip}
+ end
end
diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb
index e83fde2349..b0b7274690 100644
--- a/actionpack/test/controller/filters_test.rb
+++ b/actionpack/test/controller/filters_test.rb
@@ -1,7 +1,37 @@
require 'abstract_unit'
+require 'active_support/core_ext/symbol'
+
+class ActionController::Base
+ class << self
+ %w(append_around_filter prepend_after_filter prepend_around_filter prepend_before_filter skip_after_filter skip_before_filter skip_filter).each do |pending|
+ define_method(pending) do |*args|
+ $stderr.puts "#{pending} unimplemented: #{args.inspect}"
+ end unless method_defined?(pending)
+ end
+
+ if defined?(ActionController::Http)
+ def before_filters
+ filters = _process_action_callbacks.select { |c| c.kind == :before }
+ filters.map! { |c| c.instance_variable_get(:@raw_filter) }
+ end
+ end
+ end
+
+ if defined?(ActionController::Http)
+ def assigns(key = nil)
+ assigns = {}
+ instance_variable_names.each do |ivar|
+ next if ActionController::Base.protected_instance_variables.include?(ivar)
+ assigns[ivar[1..-1]] = instance_variable_get(ivar)
+ end
+
+ key.nil? ? assigns : assigns[key.to_s]
+ end
+ end
+end
+
+class FilterTest < ActionController::TestCase
-# FIXME: crashes Ruby 1.9
-class FilterTest < Test::Unit::TestCase
class TestController < ActionController::Base
before_filter :ensure_login
after_filter :clean_up
@@ -139,14 +169,6 @@ class FilterTest < Test::Unit::TestCase
before_filter :clean_up_tmp, :if => Proc.new { |c| false }
end
- class EmptyFilterChainController < TestController
- self.filter_chain.clear
- def show
- @action_executed = true
- render :text => "yawp!"
- end
- end
-
class PrependingController < TestController
prepend_before_filter :wonderful_life
# skip_before_filter :fire_flash
@@ -165,16 +187,21 @@ class FilterTest < Test::Unit::TestCase
def index
render :text => 'ok'
end
-
+
def public
+ render :text => 'ok'
end
end
-
+
class SkippingAndReorderingController < TestController
skip_before_filter :ensure_login
before_filter :find_record
before_filter :ensure_login
+ def index
+ render :text => 'ok'
+ end
+
private
def find_record
@ran_filter ||= []
@@ -448,11 +475,6 @@ class FilterTest < Test::Unit::TestCase
assert_equal ["filter_one", "zomg it didn't yield"], controller.assigns['filters']
end
- def test_empty_filter_chain
- assert_equal 0, EmptyFilterChainController.filter_chain.size
- assert test_process(EmptyFilterChainController).template.assigns['action_executed']
- end
-
def test_added_filter_to_inheritance_graph
assert_equal [ :ensure_login ], TestController.before_filters
end
@@ -466,88 +488,109 @@ class FilterTest < Test::Unit::TestCase
end
def test_running_filters
- assert_equal %w( wonderful_life ensure_login ), test_process(PrependingController).template.assigns["ran_filter"]
+ test_process(PrependingController)
+ assert_equal %w( wonderful_life ensure_login ), assigns["ran_filter"]
end
def test_running_filters_with_proc
- assert test_process(ProcController).template.assigns["ran_proc_filter"]
+ test_process(ProcController)
+ assert assigns["ran_proc_filter"]
end
def test_running_filters_with_implicit_proc
- assert test_process(ImplicitProcController).template.assigns["ran_proc_filter"]
+ test_process(ImplicitProcController)
+ assert assigns["ran_proc_filter"]
end
def test_running_filters_with_class
- assert test_process(AuditController).template.assigns["was_audited"]
+ test_process(AuditController)
+ assert assigns["was_audited"]
end
def test_running_anomolous_yet_valid_condition_filters
- response = test_process(AnomolousYetValidConditionController)
- assert_equal %w( ensure_login ), response.template.assigns["ran_filter"]
- assert response.template.assigns["ran_class_filter"]
- assert response.template.assigns["ran_proc_filter1"]
- assert response.template.assigns["ran_proc_filter2"]
+ test_process(AnomolousYetValidConditionController)
+ assert_equal %w( ensure_login ), assigns["ran_filter"]
+ assert assigns["ran_class_filter"]
+ assert assigns["ran_proc_filter1"]
+ assert assigns["ran_proc_filter2"]
- response = test_process(AnomolousYetValidConditionController, "show_without_filter")
- assert_equal nil, response.template.assigns["ran_filter"]
- assert !response.template.assigns["ran_class_filter"]
- assert !response.template.assigns["ran_proc_filter1"]
- assert !response.template.assigns["ran_proc_filter2"]
+ test_process(AnomolousYetValidConditionController, "show_without_filter")
+ assert_equal nil, assigns["ran_filter"]
+ assert !assigns["ran_class_filter"]
+ assert !assigns["ran_proc_filter1"]
+ assert !assigns["ran_proc_filter2"]
end
def test_running_conditional_options
- response = test_process(ConditionalOptionsFilter)
- assert_equal %w( ensure_login ), response.template.assigns["ran_filter"]
+ test_process(ConditionalOptionsFilter)
+ assert_equal %w( ensure_login ), assigns["ran_filter"]
end
def test_running_collection_condition_filters
- assert_equal %w( ensure_login ), test_process(ConditionalCollectionFilterController).template.assigns["ran_filter"]
- assert_equal nil, test_process(ConditionalCollectionFilterController, "show_without_filter").template.assigns["ran_filter"]
- assert_equal nil, test_process(ConditionalCollectionFilterController, "another_action").template.assigns["ran_filter"]
+ test_process(ConditionalCollectionFilterController)
+ assert_equal %w( ensure_login ), assigns["ran_filter"]
+ test_process(ConditionalCollectionFilterController, "show_without_filter")
+ assert_equal nil, assigns["ran_filter"]
+ test_process(ConditionalCollectionFilterController, "another_action")
+ assert_equal nil, assigns["ran_filter"]
end
def test_running_only_condition_filters
- assert_equal %w( ensure_login ), test_process(OnlyConditionSymController).template.assigns["ran_filter"]
- assert_equal nil, test_process(OnlyConditionSymController, "show_without_filter").template.assigns["ran_filter"]
+ test_process(OnlyConditionSymController)
+ assert_equal %w( ensure_login ), assigns["ran_filter"]
+ test_process(OnlyConditionSymController, "show_without_filter")
+ assert_equal nil, assigns["ran_filter"]
- assert test_process(OnlyConditionProcController).template.assigns["ran_proc_filter"]
- assert !test_process(OnlyConditionProcController, "show_without_filter").template.assigns["ran_proc_filter"]
+ test_process(OnlyConditionProcController)
+ assert assigns["ran_proc_filter"]
+ test_process(OnlyConditionProcController, "show_without_filter")
+ assert !assigns["ran_proc_filter"]
- assert test_process(OnlyConditionClassController).template.assigns["ran_class_filter"]
- assert !test_process(OnlyConditionClassController, "show_without_filter").template.assigns["ran_class_filter"]
+ test_process(OnlyConditionClassController)
+ assert assigns["ran_class_filter"]
+ test_process(OnlyConditionClassController, "show_without_filter")
+ assert !assigns["ran_class_filter"]
end
def test_running_except_condition_filters
- assert_equal %w( ensure_login ), test_process(ExceptConditionSymController).template.assigns["ran_filter"]
- assert_equal nil, test_process(ExceptConditionSymController, "show_without_filter").template.assigns["ran_filter"]
+ test_process(ExceptConditionSymController)
+ assert_equal %w( ensure_login ), assigns["ran_filter"]
+ test_process(ExceptConditionSymController, "show_without_filter")
+ assert_equal nil, assigns["ran_filter"]
- assert test_process(ExceptConditionProcController).template.assigns["ran_proc_filter"]
- assert !test_process(ExceptConditionProcController, "show_without_filter").template.assigns["ran_proc_filter"]
+ test_process(ExceptConditionProcController)
+ assert assigns["ran_proc_filter"]
+ test_process(ExceptConditionProcController, "show_without_filter")
+ assert !assigns["ran_proc_filter"]
- assert test_process(ExceptConditionClassController).template.assigns["ran_class_filter"]
- assert !test_process(ExceptConditionClassController, "show_without_filter").template.assigns["ran_class_filter"]
+ test_process(ExceptConditionClassController)
+ assert assigns["ran_class_filter"]
+ test_process(ExceptConditionClassController, "show_without_filter")
+ assert !assigns["ran_class_filter"]
end
def test_running_before_and_after_condition_filters
- assert_equal %w( ensure_login clean_up_tmp), test_process(BeforeAndAfterConditionController).template.assigns["ran_filter"]
- assert_equal nil, test_process(BeforeAndAfterConditionController, "show_without_filter").template.assigns["ran_filter"]
+ test_process(BeforeAndAfterConditionController)
+ assert_equal %w( ensure_login clean_up_tmp), assigns["ran_filter"]
+ test_process(BeforeAndAfterConditionController, "show_without_filter")
+ assert_equal nil, assigns["ran_filter"]
end
def test_around_filter
- controller = test_process(AroundFilterController)
- assert controller.template.assigns["before_ran"]
- assert controller.template.assigns["after_ran"]
+ test_process(AroundFilterController)
+ assert assigns["before_ran"]
+ assert assigns["after_ran"]
end
def test_before_after_class_filter
- controller = test_process(BeforeAfterClassFilterController)
- assert controller.template.assigns["before_ran"]
- assert controller.template.assigns["after_ran"]
+ test_process(BeforeAfterClassFilterController)
+ assert assigns["before_ran"]
+ assert assigns["after_ran"]
end
def test_having_properties_in_around_filter
- controller = test_process(AroundFilterController)
- assert_equal "before and after", controller.template.assigns["execution_log"]
+ test_process(AroundFilterController)
+ assert_equal "before and after", assigns["execution_log"]
end
def test_prepending_and_appending_around_filter
@@ -560,7 +603,7 @@ class FilterTest < Test::Unit::TestCase
def test_rendering_breaks_filtering_chain
response = test_process(RenderingController)
assert_equal "something else", response.body
- assert !response.template.assigns["ran_action"]
+ assert !assigns["ran_action"]
end
def test_filters_with_mixed_specialization_run_in_order
@@ -579,47 +622,59 @@ class FilterTest < Test::Unit::TestCase
%w(foo bar baz).each do |action|
request = ActionController::TestRequest.new
request.query_parameters[:choose] = action
- response = DynamicDispatchController.process(request, ActionController::TestResponse.new)
+ response = DynamicDispatchController.action.call(request.env).last
assert_equal action, response.body
end
end
def test_running_prepended_before_and_after_filter
- assert_equal 3, PrependingBeforeAndAfterController.filter_chain.length
- response = test_process(PrependingBeforeAndAfterController)
- assert_equal %w( before_all between_before_all_and_after_all after_all ), response.template.assigns["ran_filter"]
+ test_process(PrependingBeforeAndAfterController)
+ assert_equal %w( before_all between_before_all_and_after_all after_all ), assigns["ran_filter"]
end
-
+
def test_skipping_and_limiting_controller
- assert_equal %w( ensure_login ), test_process(SkippingAndLimitedController, "index").template.assigns["ran_filter"]
- assert_nil test_process(SkippingAndLimitedController, "public").template.assigns["ran_filter"]
+ test_process(SkippingAndLimitedController, "index")
+ assert_equal %w( ensure_login ), assigns["ran_filter"]
+ test_process(SkippingAndLimitedController, "public")
+ assert_nil assigns["ran_filter"]
end
def test_skipping_and_reordering_controller
- assert_equal %w( find_record ensure_login ), test_process(SkippingAndReorderingController, "index").template.assigns["ran_filter"]
+ test_process(SkippingAndReorderingController, "index")
+ assert_equal %w( find_record ensure_login ), assigns["ran_filter"]
end
def test_conditional_skipping_of_filters
- assert_nil test_process(ConditionalSkippingController, "login").template.assigns["ran_filter"]
- assert_equal %w( ensure_login find_user ), test_process(ConditionalSkippingController, "change_password").template.assigns["ran_filter"]
+ test_process(ConditionalSkippingController, "login")
+ assert_nil assigns["ran_filter"]
+ test_process(ConditionalSkippingController, "change_password")
+ assert_equal %w( ensure_login find_user ), assigns["ran_filter"]
- assert_nil test_process(ConditionalSkippingController, "login").template.controller.instance_variable_get("@ran_after_filter")
- assert_equal %w( clean_up ), test_process(ConditionalSkippingController, "change_password").template.controller.instance_variable_get("@ran_after_filter")
+ test_process(ConditionalSkippingController, "login")
+ assert_nil @controller.template.controller.instance_variable_get("@ran_after_filter")
+ test_process(ConditionalSkippingController, "change_password")
+ assert_equal %w( clean_up ), @controller.template.controller.instance_variable_get("@ran_after_filter")
end
def test_conditional_skipping_of_filters_when_parent_filter_is_also_conditional
- assert_equal %w( conditional_in_parent conditional_in_parent ), test_process(ChildOfConditionalParentController).template.assigns['ran_filter']
- assert_nil test_process(ChildOfConditionalParentController, 'another_action').template.assigns['ran_filter']
+ test_process(ChildOfConditionalParentController)
+ assert_equal %w( conditional_in_parent conditional_in_parent ), assigns['ran_filter']
+ test_process(ChildOfConditionalParentController, 'another_action')
+ assert_nil assigns['ran_filter']
end
def test_condition_skipping_of_filters_when_siblings_also_have_conditions
- assert_equal %w( conditional_in_parent conditional_in_parent ), test_process(ChildOfConditionalParentController).template.assigns['ran_filter'], "1"
- assert_equal nil, test_process(AnotherChildOfConditionalParentController).template.assigns['ran_filter']
- assert_equal %w( conditional_in_parent conditional_in_parent ), test_process(ChildOfConditionalParentController).template.assigns['ran_filter']
+ test_process(ChildOfConditionalParentController)
+ assert_equal %w( conditional_in_parent conditional_in_parent ), assigns['ran_filter'], "1"
+ test_process(AnotherChildOfConditionalParentController)
+ assert_equal nil, assigns['ran_filter']
+ test_process(ChildOfConditionalParentController)
+ assert_equal %w( conditional_in_parent conditional_in_parent ), assigns['ran_filter']
end
def test_changing_the_requirements
- assert_equal nil, test_process(ChangingTheRequirementsController, "go_wild").template.assigns['ran_filter']
+ test_process(ChangingTheRequirementsController, "go_wild")
+ assert_equal nil, assigns['ran_filter']
end
def test_a_rescuing_around_filter
@@ -634,11 +689,11 @@ class FilterTest < Test::Unit::TestCase
private
def test_process(controller, action = "show")
- ActionController::Base.class_eval { include ActionController::ProcessWithTest } unless ActionController::Base < ActionController::ProcessWithTest
- request = ActionController::TestRequest.new
- request.action = action
- controller = controller.new if controller.is_a?(Class)
- controller.process_with_test(request, ActionController::TestResponse.new)
+ @controller = controller.is_a?(Class) ? controller.new : controller
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+
+ process(action)
end
end
@@ -772,18 +827,9 @@ class ControllerWithTwoLessFilters < ControllerWithAllTypesOfFilters
skip_filter :after
end
-class YieldingAroundFiltersTest < Test::Unit::TestCase
+class YieldingAroundFiltersTest < ActionController::TestCase
include PostsController::AroundExceptions
- def test_filters_registering
- assert_equal 1, ControllerWithFilterMethod.filter_chain.size
- assert_equal 1, ControllerWithFilterClass.filter_chain.size
- assert_equal 1, ControllerWithFilterInstance.filter_chain.size
- assert_equal 3, ControllerWithSymbolAsFilter.filter_chain.size
- assert_equal 6, ControllerWithNestedFilters.filter_chain.size
- assert_equal 4, ControllerWithAllTypesOfFilters.filter_chain.size
- end
-
def test_base
controller = PostsController
assert_nothing_raised { test_process(controller,'no_raise') }
@@ -819,9 +865,9 @@ class YieldingAroundFiltersTest < Test::Unit::TestCase
end
def test_with_proc
- controller = test_process(ControllerWithProcFilter,'no_raise')
- assert controller.template.assigns['before']
- assert controller.template.assigns['after']
+ test_process(ControllerWithProcFilter,'no_raise')
+ assert assigns['before']
+ assert assigns['after']
end
def test_nested_filters
@@ -841,13 +887,13 @@ class YieldingAroundFiltersTest < Test::Unit::TestCase
end
def test_filter_order_with_all_filter_types
- controller = test_process(ControllerWithAllTypesOfFilters,'no_raise')
- assert_equal 'before around (before yield) around_again (before yield) around_again (after yield) around (after yield) after',controller.template.assigns['ran_filter'].join(' ')
+ test_process(ControllerWithAllTypesOfFilters,'no_raise')
+ assert_equal 'before around (before yield) around_again (before yield) around_again (after yield) around (after yield) after', assigns['ran_filter'].join(' ')
end
def test_filter_order_with_skip_filter_method
- controller = test_process(ControllerWithTwoLessFilters,'no_raise')
- assert_equal 'before around (before yield) around (after yield)',controller.template.assigns['ran_filter'].join(' ')
+ test_process(ControllerWithTwoLessFilters,'no_raise')
+ assert_equal 'before around (before yield) around (after yield)', assigns['ran_filter'].join(' ')
end
def test_first_filter_in_multiple_before_filter_chain_halts
@@ -876,10 +922,7 @@ class YieldingAroundFiltersTest < Test::Unit::TestCase
protected
def test_process(controller, action = "show")
- ActionController::Base.class_eval { include ActionController::ProcessWithTest } unless ActionController::Base < ActionController::ProcessWithTest
- request = ActionController::TestRequest.new
- request.action = action
- controller = controller.new if controller.is_a?(Class)
- controller.process_with_test(request, ActionController::TestResponse.new)
+ @controller = controller.is_a?(Class) ? controller.new : controller
+ process(action)
end
end
diff --git a/actionpack/test/controller/flash_test.rb b/actionpack/test/controller/flash_test.rb
index d8a892811e..c448f36cb3 100644
--- a/actionpack/test/controller/flash_test.rb
+++ b/actionpack/test/controller/flash_test.rb
@@ -60,6 +60,7 @@ class FlashTest < ActionController::TestCase
def std_action
@flash_copy = {}.update(flash)
+ render :nothing => true
end
def filter_halting_action
@@ -79,64 +80,84 @@ class FlashTest < ActionController::TestCase
get :set_flash
get :use_flash
- assert_equal "hello", @response.template.assigns["flash_copy"]["that"]
- assert_equal "hello", @response.template.assigns["flashy"]
+ assert_equal "hello", assigns["flash_copy"]["that"]
+ assert_equal "hello", assigns["flashy"]
get :use_flash
- assert_nil @response.template.assigns["flash_copy"]["that"], "On second flash"
+ assert_nil assigns["flash_copy"]["that"], "On second flash"
end
def test_keep_flash
get :set_flash
get :use_flash_and_keep_it
- assert_equal "hello", @response.template.assigns["flash_copy"]["that"]
- assert_equal "hello", @response.template.assigns["flashy"]
+ assert_equal "hello", assigns["flash_copy"]["that"]
+ assert_equal "hello", assigns["flashy"]
get :use_flash
- assert_equal "hello", @response.template.assigns["flash_copy"]["that"], "On second flash"
+ assert_equal "hello", assigns["flash_copy"]["that"], "On second flash"
get :use_flash
- assert_nil @response.template.assigns["flash_copy"]["that"], "On third flash"
+ assert_nil assigns["flash_copy"]["that"], "On third flash"
end
def test_flash_now
get :set_flash_now
- assert_equal "hello", @response.template.assigns["flash_copy"]["that"]
- assert_equal "bar" , @response.template.assigns["flash_copy"]["foo"]
- assert_equal "hello", @response.template.assigns["flashy"]
+ assert_equal "hello", assigns["flash_copy"]["that"]
+ assert_equal "bar" , assigns["flash_copy"]["foo"]
+ assert_equal "hello", assigns["flashy"]
get :attempt_to_use_flash_now
- assert_nil @response.template.assigns["flash_copy"]["that"]
- assert_nil @response.template.assigns["flash_copy"]["foo"]
- assert_nil @response.template.assigns["flashy"]
+ assert_nil assigns["flash_copy"]["that"]
+ assert_nil assigns["flash_copy"]["foo"]
+ assert_nil assigns["flashy"]
end
def test_update_flash
get :set_flash
get :use_flash_and_update_it
- assert_equal "hello", @response.template.assigns["flash_copy"]["that"]
- assert_equal "hello again", @response.template.assigns["flash_copy"]["this"]
+ assert_equal "hello", assigns["flash_copy"]["that"]
+ assert_equal "hello again", assigns["flash_copy"]["this"]
get :use_flash
- assert_nil @response.template.assigns["flash_copy"]["that"], "On second flash"
- assert_equal "hello again", @response.template.assigns["flash_copy"]["this"], "On second flash"
+ assert_nil assigns["flash_copy"]["that"], "On second flash"
+ assert_equal "hello again", assigns["flash_copy"]["this"], "On second flash"
end
-
+
def test_flash_after_reset_session
get :use_flash_after_reset_session
- assert_equal "hello", @response.template.assigns["flashy_that"]
- assert_equal "good-bye", @response.template.assigns["flashy_this"]
- assert_nil @response.template.assigns["flashy_that_reset"]
+ assert_equal "hello", assigns["flashy_that"]
+ assert_equal "good-bye", assigns["flashy_this"]
+ assert_nil assigns["flashy_that_reset"]
end
+ def test_does_not_set_the_session_if_the_flash_is_empty
+ get :std_action
+ assert_nil session["flash"]
+ end
+
def test_sweep_after_halted_filter_chain
get :std_action
- assert_nil @response.template.assigns["flash_copy"]["foo"]
+ assert_nil assigns["flash_copy"]["foo"]
get :filter_halting_action
- assert_equal "bar", @response.template.assigns["flash_copy"]["foo"]
+ assert_equal "bar", assigns["flash_copy"]["foo"]
get :std_action # follow redirection
- assert_equal "bar", @response.template.assigns["flash_copy"]["foo"]
+ assert_equal "bar", assigns["flash_copy"]["foo"]
get :std_action
- assert_nil @response.template.assigns["flash_copy"]["foo"]
+ assert_nil assigns["flash_copy"]["foo"]
+ end
+
+ def test_keep_and_discard_return_values
+ flash = ActionController::Flash::FlashHash.new
+ flash.update(:foo => :foo_indeed, :bar => :bar_indeed)
+
+ assert_equal(:foo_indeed, flash.discard(:foo)) # valid key passed
+ assert_nil flash.discard(:unknown) # non existant key passed
+ assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.discard()) # nothing passed
+ assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.discard(nil)) # nothing passed
+
+ assert_equal(:foo_indeed, flash.keep(:foo)) # valid key passed
+ assert_nil flash.keep(:unknown) # non existant key passed
+ assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.keep()) # nothing passed
+ assert_equal({:foo => :foo_indeed, :bar => :bar_indeed}, flash.keep(nil)) # nothing passed
end
end
diff --git a/actionpack/test/controller/helper_test.rb b/actionpack/test/controller/helper_test.rb
index 5f36461b89..5b9feb3630 100644
--- a/actionpack/test/controller/helper_test.rb
+++ b/actionpack/test/controller/helper_test.rb
@@ -1,4 +1,5 @@
require 'abstract_unit'
+require 'active_support/core_ext/kernel/reporting'
ActionController::Base.helpers_dir = File.dirname(__FILE__) + '/../fixtures/helpers'
@@ -26,7 +27,7 @@ module Fun
end
end
-class ApplicationController < ActionController::Base
+class AllHelpersController < ActionController::Base
helper :all
end
@@ -101,24 +102,32 @@ class HelperTest < Test::Unit::TestCase
assert master_helper_methods.include?('delegate_attr=')
end
- def test_helper_for_nested_controller
+ def call_controller(klass, action)
request = ActionController::TestRequest.new
- response = ActionController::TestResponse.new
- request.action = 'render_hello_world'
+ klass.action(action).call(request.env)
+ end
- assert_equal 'hello: Iz guuut!', Fun::GamesController.process(request, response).body
+ def test_helper_for_nested_controller
+ assert_equal 'hello: Iz guuut!',
+ call_controller(Fun::GamesController, "render_hello_world").last.body
+ # request = ActionController::TestRequest.new
+ #
+ # resp = Fun::GamesController.action(:render_hello_world).call(request.env)
+ # assert_equal 'hello: Iz guuut!', resp.last.body
end
def test_helper_for_acronym_controller
- request = ActionController::TestRequest.new
- response = ActionController::TestResponse.new
- request.action = 'test'
-
- assert_equal 'test: baz', Fun::PdfController.process(request, response).body
+ assert_equal "test: baz", call_controller(Fun::PdfController, "test").last.body
+ #
+ # request = ActionController::TestRequest.new
+ # response = ActionController::TestResponse.new
+ # request.action = 'test'
+ #
+ # assert_equal 'test: baz', Fun::PdfController.process(request, response).body
end
def test_all_helpers
- methods = ApplicationController.master_helper_module.instance_methods.map(&:to_s)
+ methods = AllHelpersController.master_helper_module.instance_methods.map(&:to_s)
# abc_helper.rb
assert methods.include?('bare_a')
@@ -145,7 +154,7 @@ class HelperTest < Test::Unit::TestCase
end
def test_helper_proxy
- methods = ApplicationController.helpers.methods.map(&:to_s)
+ methods = AllHelpersController.helpers.methods.map(&:to_s)
# ActionView
assert methods.include?('pluralize')
@@ -204,6 +213,11 @@ class IsolatedHelpersTest < Test::Unit::TestCase
end
end
+ def call_controller(klass, action)
+ request = ActionController::TestRequest.new
+ klass.action(action).call(request.env)
+ end
+
def setup
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
@@ -211,14 +225,14 @@ class IsolatedHelpersTest < Test::Unit::TestCase
end
def test_helper_in_a
- assert_raise(NameError) { A.process(@request, @response) }
+ assert_raise(ActionView::TemplateError) { call_controller(A, "index") }
end
def test_helper_in_b
- assert_equal 'B', B.process(@request, @response).body
+ assert_equal 'B', call_controller(B, "index").last.body
end
def test_helper_in_c
- assert_equal 'C', C.process(@request, @response).body
+ assert_equal 'C', call_controller(C, "index").last.body
end
end
diff --git a/actionpack/test/controller/http_digest_authentication_test.rb b/actionpack/test/controller/http_digest_authentication_test.rb
index 00789eea38..15a11395bb 100644
--- a/actionpack/test/controller/http_digest_authentication_test.rb
+++ b/actionpack/test/controller/http_digest_authentication_test.rb
@@ -38,6 +38,15 @@ class HttpDigestAuthenticationTest < ActionController::TestCase
tests DummyDigestController
+ setup do
+ # Used as secret in generating nonce to prevent tampering of timestamp
+ @old_secret, ActionController::Base.session_options[:secret] = ActionController::Base.session_options[:secret], "session_options_secret"
+ end
+
+ teardown do
+ ActionController::Base.session_options[:secret] = @old_secret
+ end
+
AUTH_HEADERS.each do |header|
test "successful authentication with #{header.downcase}" do
@request.env[header] = encode_credentials(:username => 'lifo', :password => 'world')
@@ -111,8 +120,6 @@ class HttpDigestAuthenticationTest < ActionController::TestCase
test "authentication request with valid credential and nil session" do
@request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please')
- # session_id = "" in functional test, but is +nil+ in real life
- @request.session.session_id = nil
get :display
assert_response :success
@@ -151,25 +158,38 @@ class HttpDigestAuthenticationTest < ActionController::TestCase
assert_equal 'Definitely Maybe', @response.body
end
+ test "authentication request with _method" do
+ @request.env['HTTP_AUTHORIZATION'] = encode_credentials(:username => 'pretty', :password => 'please', :method => :post)
+ @request.env['rack.methodoverride.original_method'] = 'POST'
+ put :display
+
+ assert_response :success
+ assert assigns(:logged_in)
+ assert_equal 'Definitely Maybe', @response.body
+ end
+
private
def encode_credentials(options)
options.reverse_merge!(:nc => "00000001", :cnonce => "0a4f113b", :password_is_ha1 => false)
password = options.delete(:password)
- # Set in /initializers/session_store.rb. Used as secret in generating nonce
- # to prevent tampering of timestamp
- ActionController::Base.session_options[:secret] = "session_options_secret"
+ # Perform unauthenticated request to retrieve digest parameters to use on subsequent request
+ method = options.delete(:method) || 'GET'
- # Perform unauthenticated GET to retrieve digest parameters to use on subsequent request
- get :index
+ case method.to_s.upcase
+ when 'GET'
+ get :index
+ when 'POST'
+ post :index
+ end
assert_response :unauthorized
credentials = decode_credentials(@response.headers['WWW-Authenticate'])
credentials.merge!(options)
credentials.reverse_merge!(:uri => "#{@request.env['REQUEST_URI']}")
- ActionController::HttpAuthentication::Digest.encode_credentials("GET", credentials, password, options[:password_is_ha1])
+ ActionController::HttpAuthentication::Digest.encode_credentials(method, credentials, password, options[:password_is_ha1])
end
def decode_credentials(header)
diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb
index e39a934c24..197ba0c69c 100644
--- a/actionpack/test/controller/integration_test.rb
+++ b/actionpack/test/controller/integration_test.rb
@@ -1,4 +1,5 @@
require 'abstract_unit'
+require 'action_controller/vendor/html-scanner'
class SessionTest < Test::Unit::TestCase
StubApp = lambda { |env|
@@ -30,7 +31,7 @@ class SessionTest < Test::Unit::TestCase
def test_request_via_redirect_uses_given_method
path = "/somepath"; args = {:id => '1'}; headers = {"X-Test-Header" => "testvalue"}
- @session.expects(:put).with(path, args, headers)
+ @session.expects(:process).with(:put, path, args, headers)
@session.stubs(:redirect?).returns(false)
@session.request_via_redirect(:put, path, args, headers)
end
@@ -90,16 +91,6 @@ class SessionTest < Test::Unit::TestCase
assert_equal '/show', @session.url_for(options)
end
- def test_redirect_bool_with_status_in_300s
- @session.stubs(:status).returns 301
- assert @session.redirect?
- end
-
- def test_redirect_bool_with_status_in_200s
- @session.stubs(:status).returns 200
- assert !@session.redirect?
- end
-
def test_get
path = "/index"; params = "blah"; headers = {:location => 'blah'}
@session.expects(:process).with(:get,path,params,headers)
@@ -133,8 +124,8 @@ class SessionTest < Test::Unit::TestCase
def test_xml_http_request_get
path = "/index"; params = "blah"; headers = {:location => 'blah'}
headers_after_xhr = headers.merge(
- "X-Requested-With" => "XMLHttpRequest",
- "Accept" => "text/javascript, text/html, application/xml, text/xml, */*"
+ "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest",
+ "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*"
)
@session.expects(:process).with(:get,path,params,headers_after_xhr)
@session.xml_http_request(:get,path,params,headers)
@@ -143,8 +134,8 @@ class SessionTest < Test::Unit::TestCase
def test_xml_http_request_post
path = "/index"; params = "blah"; headers = {:location => 'blah'}
headers_after_xhr = headers.merge(
- "X-Requested-With" => "XMLHttpRequest",
- "Accept" => "text/javascript, text/html, application/xml, text/xml, */*"
+ "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest",
+ "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*"
)
@session.expects(:process).with(:post,path,params,headers_after_xhr)
@session.xml_http_request(:post,path,params,headers)
@@ -153,8 +144,8 @@ class SessionTest < Test::Unit::TestCase
def test_xml_http_request_put
path = "/index"; params = "blah"; headers = {:location => 'blah'}
headers_after_xhr = headers.merge(
- "X-Requested-With" => "XMLHttpRequest",
- "Accept" => "text/javascript, text/html, application/xml, text/xml, */*"
+ "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest",
+ "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*"
)
@session.expects(:process).with(:put,path,params,headers_after_xhr)
@session.xml_http_request(:put,path,params,headers)
@@ -163,8 +154,8 @@ class SessionTest < Test::Unit::TestCase
def test_xml_http_request_delete
path = "/index"; params = "blah"; headers = {:location => 'blah'}
headers_after_xhr = headers.merge(
- "X-Requested-With" => "XMLHttpRequest",
- "Accept" => "text/javascript, text/html, application/xml, text/xml, */*"
+ "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest",
+ "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*"
)
@session.expects(:process).with(:delete,path,params,headers_after_xhr)
@session.xml_http_request(:delete,path,params,headers)
@@ -173,17 +164,17 @@ class SessionTest < Test::Unit::TestCase
def test_xml_http_request_head
path = "/index"; params = "blah"; headers = {:location => 'blah'}
headers_after_xhr = headers.merge(
- "X-Requested-With" => "XMLHttpRequest",
- "Accept" => "text/javascript, text/html, application/xml, text/xml, */*"
+ "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest",
+ "HTTP_ACCEPT" => "text/javascript, text/html, application/xml, text/xml, */*"
)
@session.expects(:process).with(:head,path,params,headers_after_xhr)
@session.xml_http_request(:head,path,params,headers)
end
def test_xml_http_request_override_accept
- path = "/index"; params = "blah"; headers = {:location => 'blah', "Accept" => "application/xml"}
+ path = "/index"; params = "blah"; headers = {:location => 'blah', "HTTP_ACCEPT" => "application/xml"}
headers_after_xhr = headers.merge(
- "X-Requested-With" => "XMLHttpRequest"
+ "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest"
)
@session.expects(:process).with(:post,path,params,headers_after_xhr)
@session.xml_http_request(:post,path,params,headers)
@@ -263,7 +254,7 @@ class IntegrationProcessTest < ActionController::IntegrationTest
assert_response 200
assert_response :success
assert_response :ok
- assert_equal({}, cookies)
+ assert_equal({}, cookies.to_hash)
assert_equal "OK", body
assert_equal "OK", response.body
assert_kind_of HTML::Document, html_document
@@ -279,7 +270,7 @@ class IntegrationProcessTest < ActionController::IntegrationTest
assert_response 201
assert_response :success
assert_response :created
- assert_equal({}, cookies)
+ assert_equal({}, cookies.to_hash)
assert_equal "Created", body
assert_equal "Created", response.body
assert_kind_of HTML::Document, html_document
@@ -297,7 +288,7 @@ class IntegrationProcessTest < ActionController::IntegrationTest
assert_response 410
assert_response :gone
assert_equal "cookie_1=; path=/\ncookie_3=chocolate; path=/", headers["Set-Cookie"]
- assert_equal({"cookie_1"=>"", "cookie_2"=>"oatmeal", "cookie_3"=>"chocolate"}, cookies)
+ assert_equal({"cookie_1"=>"", "cookie_2"=>"oatmeal", "cookie_3"=>"chocolate"}, cookies.to_hash)
assert_equal "Gone", response.body
end
end
@@ -337,7 +328,7 @@ class IntegrationProcessTest < ActionController::IntegrationTest
get '/get_with_params?foo=bar'
assert_equal '/get_with_params?foo=bar', request.env["REQUEST_URI"]
assert_equal '/get_with_params?foo=bar', request.request_uri
- assert_equal "", request.env["QUERY_STRING"]
+ assert_equal "foo=bar", request.env["QUERY_STRING"]
assert_equal 'foo=bar', request.query_string
assert_equal 'bar', request.parameters['foo']
diff --git a/actionpack/test/controller/layout_test.rb b/actionpack/test/controller/layout_test.rb
index f2721e274d..cb9bdf57bb 100644
--- a/actionpack/test/controller/layout_test.rb
+++ b/actionpack/test/controller/layout_test.rb
@@ -9,8 +9,11 @@ ActionView::Template::register_template_handler :mab,
ActionController::Base.view_paths = [ File.dirname(__FILE__) + '/../fixtures/layout_tests/' ]
+require "fixture_template"
+
class LayoutTest < ActionController::Base
def self.controller_path; 'views' end
+ def self._implied_layout_name; to_s.underscore.gsub(/_controller$/, '') ; end
self.view_paths = ActionController::Base.view_paths.dup
end
@@ -35,6 +38,15 @@ end
class MultipleExtensions < LayoutTest
end
+if defined?(ActionController::Http)
+ LayoutTest._write_layout_method
+ ProductController._write_layout_method
+ ItemController._write_layout_method
+ ThirdPartyTemplateLibraryController._write_layout_method
+ MultipleExtensions._write_layout_method
+ ControllerNameSpace::NestedController._write_layout_method
+end
+
class LayoutAutoDiscoveryTest < ActionController::TestCase
def setup
super
@@ -56,23 +68,19 @@ class LayoutAutoDiscoveryTest < ActionController::TestCase
def test_third_party_template_library_auto_discovers_layout
@controller = ThirdPartyTemplateLibraryController.new
get :hello
- assert_equal 'layouts/third_party_template_library.mab', @controller.active_layout(true).to_s
- assert_equal 'layouts/third_party_template_library', @response.layout
assert_response :success
- assert_equal 'Mab', @response.body
+ assert_equal 'layouts/third_party_template_library.mab', @response.body
end
- def test_namespaced_controllers_auto_detect_layouts
+ def test_namespaced_controllers_auto_detect_layouts1
@controller = ControllerNameSpace::NestedController.new
get :hello
- assert_equal 'layouts/controller_name_space/nested', @controller.active_layout(true).to_s
assert_equal 'controller_name_space/nested.rhtml hello.rhtml', @response.body
end
- def test_namespaced_controllers_auto_detect_layouts
+ def test_namespaced_controllers_auto_detect_layouts2
@controller = MultipleExtensions.new
get :hello
- assert_equal 'layouts/multiple_extensions.html.erb', @controller.active_layout(true).to_s
assert_equal 'multiple_extensions.html.erb hello.rhtml', @response.body.strip
end
end
@@ -116,70 +124,75 @@ class RendersNoLayoutController < LayoutTest
end
class LayoutSetInResponseTest < ActionController::TestCase
+ include ActionView::TemplateHandlers
+
def test_layout_set_when_using_default_layout
@controller = DefaultLayoutController.new
get :hello
- assert_equal 'layouts/layout_test', @response.layout
+ assert @controller.template.layout.include?('layouts/layout_test')
end
def test_layout_set_when_set_in_controller
@controller = HasOwnLayoutController.new
get :hello
- assert_equal 'layouts/item', @response.layout
+ assert @controller.template.layout.include?('layouts/item')
end
def test_layout_only_exception_when_included
@controller = OnlyLayoutController.new
get :hello
- assert_equal 'layouts/item', @response.layout
+ assert @controller.template.layout.include?('layouts/item')
end
def test_layout_only_exception_when_excepted
@controller = OnlyLayoutController.new
get :goodbye
- assert_equal nil, @response.layout
+ assert !@response.body.include?("item.rhtml"), "#{@response.body.inspect} included 'item.rhtml'"
end
def test_layout_except_exception_when_included
@controller = ExceptLayoutController.new
get :hello
- assert_equal 'layouts/item', @response.layout
+ assert @controller.template.layout.include?('layouts/item')
end
def test_layout_except_exception_when_excepted
@controller = ExceptLayoutController.new
get :goodbye
- assert_equal nil, @response.layout
+ assert !@response.body.include?("item.rhtml"), "#{@response.body.inspect} included 'item.rhtml'"
end
def test_layout_set_when_using_render
@controller = SetsLayoutInRenderController.new
get :hello
- assert_equal 'layouts/third_party_template_library', @response.layout
+ assert @controller.template.layout.include?('layouts/third_party_template_library')
end
def test_layout_is_not_set_when_none_rendered
@controller = RendersNoLayoutController.new
get :hello
- assert_nil @response.layout
+ assert_nil @controller.template.layout
end
- def test_exempt_from_layout_honored_by_render_template
- ActionController::Base.exempt_from_layout :rhtml
- @controller = RenderWithTemplateOptionController.new
+ for_tag(:old_base) do
+ # exempt_from_layout is deprecated
+ def test_exempt_from_layout_honored_by_render_template
+ ActionController::Base.exempt_from_layout :erb
+ @controller = RenderWithTemplateOptionController.new
- get :hello
- assert_equal "alt/hello.rhtml", @response.body.strip
+ get :hello
+ assert_equal "alt/hello.rhtml", @response.body.strip
- ensure
- ActionController::Base.exempt_from_layout.delete(/\.rhtml$/)
+ ensure
+ ActionController::Base.exempt_from_layout.delete(ERB)
+ end
end
def test_layout_is_picked_from_the_controller_instances_view_path
pending do
@controller = PrependsViewPathController.new
get :hello
- assert_equal 'layouts/alt', @response.layout
+ assert_equal 'layouts/alt', @controller.template.layout
end
end
@@ -203,8 +216,7 @@ end
class LayoutExceptionRaised < ActionController::TestCase
def test_exception_raised_when_layout_file_not_found
@controller = SetsNonExistentLayoutFile.new
- get :hello
- assert_kind_of ActionView::MissingTemplate, @response.template.instance_eval { @exception }
+ assert_raise(ActionView::MissingTemplate) { get :hello }
end
end
@@ -232,7 +244,7 @@ unless RUBY_PLATFORM =~ /(:?mswin|mingw|bccwin)/
@controller = LayoutSymlinkedTest.new
get :hello
assert_response 200
- assert_equal "layouts/symlinked/symlinked_layout", @response.layout
+ assert @controller.template.layout.include?("layouts/symlinked/symlinked_layout")
end
end
end
diff --git a/actionpack/test/controller/logging_test.rb b/actionpack/test/controller/logging_test.rb
index 1f3ff4ef52..a7ed1b8665 100644
--- a/actionpack/test/controller/logging_test.rb
+++ b/actionpack/test/controller/logging_test.rb
@@ -11,6 +11,11 @@ class LoggingTest < ActionController::TestCase
class MockLogger
attr_reader :logged
+ attr_accessor :level
+
+ def initialize
+ @level = Logger::DEBUG
+ end
def method_missing(method, *args)
@logged ||= []
@@ -30,7 +35,7 @@ class LoggingTest < ActionController::TestCase
end
def test_logging_with_parameters
- get :show, :id => 10
+ get :show, :id => '10'
assert_equal 3, logs.size
params = logs.detect {|l| l =~ /Parameters/ }
@@ -44,6 +49,6 @@ class LoggingTest < ActionController::TestCase
end
def logs
- @logs ||= @controller.logger.logged.compact.map {|l| l.strip}
+ @logs ||= @controller.logger.logged.compact.map {|l| l.to_s.strip}
end
end
diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb
index 7cd5145a2f..56b49251c6 100644
--- a/actionpack/test/controller/mime_responds_test.rb
+++ b/actionpack/test/controller/mime_responds_test.rb
@@ -375,9 +375,11 @@ class MimeControllerTest < ActionController::TestCase
end
def test_rjs_type_skips_layout
- @request.accept = "text/javascript"
- get :all_types_with_layout
- assert_equal 'RJS for all_types_with_layout', @response.body
+ pending(:new_base) do
+ @request.accept = "text/javascript"
+ get :all_types_with_layout
+ assert_equal 'RJS for all_types_with_layout', @response.body
+ end
end
def test_html_type_with_layout
@@ -437,7 +439,7 @@ class MimeControllerTest < ActionController::TestCase
@controller.instance_eval do
def render(*args)
unless args.empty?
- @action = args.first[:action]
+ @action = args.first[:action] || action_name
end
response.body = "#{@action} - #{@template.formats}"
end
@@ -490,14 +492,15 @@ class PostController < AbstractPostController
end
end
- protected
- def with_iphone
- Mime::Type.register_alias("text/html", :iphone)
- request.format = "iphone" if request.env["HTTP_ACCEPT"] == "text/iphone"
- yield
- ensure
- Mime.module_eval { remove_const :IPHONE if const_defined?(:IPHONE) }
- end
+protected
+
+ def with_iphone
+ Mime::Type.register_alias("text/html", :iphone)
+ request.format = "iphone" if request.env["HTTP_ACCEPT"] == "text/iphone"
+ yield
+ ensure
+ Mime.module_eval { remove_const :IPHONE if const_defined?(:IPHONE) }
+ end
end
class SuperPostController < PostController
@@ -509,6 +512,11 @@ class SuperPostController < PostController
end
end
+if defined?(ActionController::Http)
+ PostController._write_layout_method
+ SuperPostController._write_layout_method
+end
+
class MimeControllerLayoutsTest < ActionController::TestCase
tests PostController
@@ -526,14 +534,16 @@ class MimeControllerLayoutsTest < ActionController::TestCase
assert_equal 'Hello iPhone', @response.body
end
- def test_format_with_inherited_layouts
- @controller = SuperPostController.new
+ for_tag(:old_base) do
+ def test_format_with_inherited_layouts
+ @controller = SuperPostController.new
- get :index
- assert_equal 'Super Firefox', @response.body
+ get :index
+ assert_equal 'Super Firefox', @response.body
- @request.accept = "text/iphone"
- get :index
- assert_equal '<html><div id="super_iphone">Super iPhone</div></html>', @response.body
+ @request.accept = "text/iphone"
+ get :index
+ assert_equal '<html><div id="super_iphone">Super iPhone</div></html>', @response.body
+ end
end
end
diff --git a/actionpack/test/controller/redirect_test.rb b/actionpack/test/controller/redirect_test.rb
index 91e21db854..13247f2d08 100644
--- a/actionpack/test/controller/redirect_test.rb
+++ b/actionpack/test/controller/redirect_test.rb
@@ -233,11 +233,6 @@ class RedirectTest < ActionController::TestCase
assert_redirected_to Workshop.new(5, true)
end
- def test_redirect_with_partial_params
- get :module_redirect
- assert_redirected_to :action => 'hello_world'
- end
-
def test_redirect_to_nil
assert_raise(ActionController::ActionControllerError) do
get :redirect_to_nil
diff --git a/actionpack/test/controller/render_js_test.rb b/actionpack/test/controller/render_js_test.rb
new file mode 100644
index 0000000000..d02fd3fd4c
--- /dev/null
+++ b/actionpack/test/controller/render_js_test.rb
@@ -0,0 +1,39 @@
+require 'abstract_unit'
+require 'controller/fake_models'
+require 'pathname'
+
+class TestController < ActionController::Base
+ protect_from_forgery
+
+ def render_vanilla_js_hello
+ render :js => "alert('hello')"
+ end
+
+ def greeting
+ # let's just rely on the template
+ end
+
+ def partial
+ render :partial => 'partial'
+ end
+end
+
+class RenderTest < ActionController::TestCase
+ tests TestController
+
+ def test_render_vanilla_js
+ get :render_vanilla_js_hello
+ assert_equal "alert('hello')", @response.body
+ assert_equal "text/javascript", @response.content_type
+ end
+
+ def test_render_with_default_from_accept_header
+ xhr :get, :greeting
+ assert_equal "$(\"body\").visualEffect(\"highlight\");", @response.body
+ end
+
+ def test_should_render_js_partial
+ xhr :get, :partial, :format => 'js'
+ assert_equal 'partial js', @response.body
+ end
+end \ No newline at end of file
diff --git a/actionpack/test/controller/render_json_test.rb b/actionpack/test/controller/render_json_test.rb
new file mode 100644
index 0000000000..233b2dfd89
--- /dev/null
+++ b/actionpack/test/controller/render_json_test.rb
@@ -0,0 +1,80 @@
+require 'abstract_unit'
+require 'controller/fake_models'
+require 'pathname'
+
+class TestController < ActionController::Base
+ protect_from_forgery
+
+ def render_json_nil
+ render :json => nil
+ end
+
+ def render_json_hello_world
+ render :json => ActiveSupport::JSON.encode(:hello => 'world')
+ end
+
+ def render_json_hello_world_with_callback
+ render :json => ActiveSupport::JSON.encode(:hello => 'world'), :callback => 'alert'
+ end
+
+ def render_json_with_custom_content_type
+ render :json => ActiveSupport::JSON.encode(:hello => 'world'), :content_type => 'text/javascript'
+ end
+
+ def render_symbol_json
+ render :json => ActiveSupport::JSON.encode(:hello => 'world')
+ end
+
+ def render_json_with_render_to_string
+ render :json => {:hello => render_to_string(:partial => 'partial')}
+ end
+end
+
+class RenderTest < ActionController::TestCase
+ tests TestController
+
+ def setup
+ # 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)
+
+ @request.host = "www.nextangle.com"
+ end
+
+ def test_render_json_nil
+ get :render_json_nil
+ assert_equal 'null', @response.body
+ assert_equal 'application/json', @response.content_type
+ end
+
+ def test_render_json
+ get :render_json_hello_world
+ assert_equal '{"hello":"world"}', @response.body
+ assert_equal 'application/json', @response.content_type
+ end
+
+ def test_render_json_with_callback
+ get :render_json_hello_world_with_callback
+ assert_equal 'alert({"hello":"world"})', @response.body
+ assert_equal 'application/json', @response.content_type
+ end
+
+ def test_render_json_with_custom_content_type
+ get :render_json_with_custom_content_type
+ assert_equal '{"hello":"world"}', @response.body
+ assert_equal 'text/javascript', @response.content_type
+ end
+
+ def test_render_symbol_json
+ get :render_symbol_json
+ assert_equal '{"hello":"world"}', @response.body
+ assert_equal 'application/json', @response.content_type
+ end
+
+ def test_render_json_with_render_to_string
+ get :render_json_with_render_to_string
+ assert_equal '{"hello":"partial html"}', @response.body
+ assert_equal 'application/json', @response.content_type
+ end
+end \ No newline at end of file
diff --git a/actionpack/test/controller/render_other_test.rb b/actionpack/test/controller/render_other_test.rb
new file mode 100644
index 0000000000..05645e47fa
--- /dev/null
+++ b/actionpack/test/controller/render_other_test.rb
@@ -0,0 +1,238 @@
+require 'abstract_unit'
+require 'controller/fake_models'
+require 'pathname'
+
+class TestController < ActionController::Base
+ protect_from_forgery
+ layout :determine_layout
+
+ module RenderTestHelper
+ def rjs_helper_method_from_module
+ page.visual_effect :highlight
+ end
+ end
+
+ helper RenderTestHelper
+ helper do
+ def rjs_helper_method(value)
+ page.visual_effect :highlight, value
+ end
+ end
+
+ def enum_rjs_test
+ render :update do |page|
+ page.select('.product').each do |value|
+ page.rjs_helper_method_from_module
+ page.rjs_helper_method(value)
+ page.sortable(value, :url => { :action => "order" })
+ page.draggable(value)
+ end
+ end
+ end
+
+ def render_explicit_html_template
+ end
+
+ def render_custom_code_rjs
+ render :update, :status => 404 do |page|
+ page.replace :foo, :partial => 'partial'
+ end
+ end
+
+ def render_implicit_html_template
+ end
+
+ def render_js_with_explicit_template
+ @project_id = 4
+ render :template => 'test/delete_with_js'
+ end
+
+ def render_js_with_explicit_action_template
+ @project_id = 4
+ render :action => 'delete_with_js'
+ end
+
+ def delete_with_js
+ @project_id = 4
+ end
+
+ def update_page
+ render :update do |page|
+ page.replace_html 'balance', '$37,000,000.00'
+ page.visual_effect :highlight, 'balance'
+ end
+ end
+
+ def update_page_with_instance_variables
+ @money = '$37,000,000.00'
+ @div_id = 'balance'
+ render :update do |page|
+ page.replace_html @div_id, @money
+ page.visual_effect :highlight, @div_id
+ end
+ end
+
+ def update_page_with_view_method
+ render :update do |page|
+ page.replace_html 'person', pluralize(2, 'person')
+ end
+ end
+
+ def partial_as_rjs
+ render :update do |page|
+ page.replace :foo, :partial => 'partial'
+ end
+ end
+
+ def respond_to_partial_as_rjs
+ respond_to do |format|
+ format.js do
+ render :update do |page|
+ page.replace :foo, :partial => 'partial'
+ end
+ end
+ end
+ end
+
+ def render_alternate_default
+ # For this test, the method "default_render" is overridden:
+ @alternate_default_render = lambda do
+ render :update do |page|
+ page.replace :foo, :partial => 'partial'
+ end
+ end
+ end
+
+private
+ def default_render
+ if @alternate_default_render
+ @alternate_default_render.call
+ else
+ super
+ end
+ end
+
+ def determine_layout
+ case action_name
+ when "hello_world", "layout_test", "rendering_without_layout",
+ "rendering_nothing_on_layout", "render_text_hello_world",
+ "render_text_hello_world_with_layout",
+ "hello_world_with_layout_false",
+ "partial_only", "partial_only_with_layout",
+ "accessing_params_in_template",
+ "accessing_params_in_template_with_layout",
+ "render_with_explicit_template",
+ "render_with_explicit_string_template",
+ "update_page", "update_page_with_instance_variables"
+
+ "layouts/standard"
+ when "action_talk_to_layout", "layout_overriding_layout"
+ "layouts/talk_from_action"
+ when "render_implicit_html_template_from_xhr_request"
+ (request.xhr? ? 'layouts/xhr' : 'layouts/standard')
+ end
+ end
+end
+
+class RenderTest < ActionController::TestCase
+ tests TestController
+
+ def setup
+ # 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)
+
+ @request.host = "www.nextangle.com"
+ end
+
+ def test_enum_rjs_test
+ ActiveSupport::SecureRandom.stubs(:base64).returns("asdf")
+ get :enum_rjs_test
+ body = %{
+ $$(".product").each(function(value, index) {
+ new Effect.Highlight(element,{});
+ new Effect.Highlight(value,{});
+ Sortable.create(value, {onUpdate:function(){new Ajax.Request('/test/order', {asynchronous:true, evalScripts:true, parameters:Sortable.serialize(value) + '&authenticity_token=' + encodeURIComponent('asdf')})}});
+ new Draggable(value, {});
+ });
+ }.gsub(/^ /, '').strip
+ assert_equal body, @response.body
+ end
+
+ def test_explicitly_rendering_an_html_template_with_implicit_html_template_renders_should_be_possible_from_an_rjs_template
+ [:js, "js"].each do |format|
+ assert_nothing_raised do
+ get :render_explicit_html_template, :format => format
+ assert_equal %(document.write("Hello world\\n");), @response.body
+ end
+ end
+ end
+
+ def test_render_custom_code_rjs
+ get :render_custom_code_rjs
+ assert_response 404
+ assert_equal %(Element.replace("foo", "partial html");), @response.body
+ end
+
+ def test_render_in_an_rjs_template_should_pick_html_templates_when_available
+ [:js, "js"].each do |format|
+ assert_nothing_raised do
+ get :render_implicit_html_template, :format => format
+ assert_equal %(document.write("Hello world\\n");), @response.body
+ end
+ end
+ end
+
+ def test_render_rjs_template_explicitly
+ get :render_js_with_explicit_template
+ assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body
+ end
+
+ def test_rendering_rjs_action_explicitly
+ get :render_js_with_explicit_action_template
+ assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body
+ end
+
+ def test_render_rjs_with_default
+ get :delete_with_js
+ assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body
+ end
+
+ def test_update_page
+ get :update_page
+ assert_template nil
+ assert_equal 'text/javascript; charset=utf-8', @response.headers['Content-Type']
+ assert_equal 2, @response.body.split($/).length
+ end
+
+ def test_update_page_with_instance_variables
+ get :update_page_with_instance_variables
+ assert_template nil
+ assert_equal 'text/javascript; charset=utf-8', @response.headers["Content-Type"]
+ assert_match /balance/, @response.body
+ assert_match /\$37/, @response.body
+ end
+
+ def test_update_page_with_view_method
+ get :update_page_with_view_method
+ assert_template nil
+ assert_equal 'text/javascript; charset=utf-8', @response.headers["Content-Type"]
+ assert_match /2 people/, @response.body
+ end
+
+ def test_should_render_html_formatted_partial_with_rjs
+ xhr :get, :partial_as_rjs
+ assert_equal %(Element.replace("foo", "partial html");), @response.body
+ end
+
+ def test_should_render_html_formatted_partial_with_rjs_and_js_format
+ xhr :get, :respond_to_partial_as_rjs
+ assert_equal %(Element.replace("foo", "partial html");), @response.body
+ end
+
+ def test_should_render_with_alternate_default_render
+ xhr :get, :render_alternate_default
+ assert_equal %(Element.replace("foo", "partial html");), @response.body
+ end
+end \ No newline at end of file
diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb
index 9a34bcebe6..9e42d1738a 100644
--- a/actionpack/test/controller/render_test.rb
+++ b/actionpack/test/controller/render_test.rb
@@ -1,8 +1,10 @@
require 'abstract_unit'
require 'controller/fake_models'
+require 'pathname'
module Fun
class GamesController < ActionController::Base
+ # :ported:
def hello_world
end
end
@@ -79,6 +81,7 @@ class TestController < ActionController::Base
fresh_when(:last_modified => Time.now.utc.beginning_of_day, :etag => [ :foo, 123 ])
end
+ # :ported:
def render_hello_world
render :template => "test/hello_world"
end
@@ -93,23 +96,28 @@ class TestController < ActionController::Base
render :template => "test/hello_world"
end
+ # :ported: compatibility
def render_hello_world_with_forward_slash
render :template => "/test/hello_world"
end
+ # :ported:
def render_template_in_top_directory
render :template => 'shared'
end
+ # :deprecated:
def render_template_in_top_directory_with_slash
render :template => '/shared'
end
+ # :ported:
def render_hello_world_from_variable
@person = "david"
render :text => "hello #{@person}"
end
+ # :ported:
def render_action_hello_world
render :action => "hello_world"
end
@@ -122,10 +130,12 @@ class TestController < ActionController::Base
render :action => :hello_world
end
+ # :ported:
def render_text_hello_world
render :text => "hello world"
end
+ # :ported:
def render_text_hello_world_with_layout
@variable_for_layout = ", I'm here!"
render :text => "hello world", :layout => true
@@ -135,18 +145,21 @@ class TestController < ActionController::Base
render :layout => false
end
+ # :ported:
def render_file_with_instance_variables
@secret = 'in the sauce'
path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb')
render :file => path
end
+ # :ported:
def render_file_as_string_with_instance_variables
@secret = 'in the sauce'
path = File.expand_path(File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb'))
render path
end
+ # :ported:
def render_file_not_using_full_path
@secret = 'in the sauce'
render :file => 'test/render_file_with_ivar'
@@ -193,52 +206,30 @@ class TestController < ActionController::Base
render :inline => "<%= controller_name %>"
end
- def render_json_hello_world
- render :json => {:hello => 'world'}.to_json
- end
-
- def render_json_hello_world_with_callback
- render :json => {:hello => 'world'}.to_json, :callback => 'alert'
- end
-
- def render_json_with_custom_content_type
- render :json => {:hello => 'world'}.to_json, :content_type => 'text/javascript'
- end
-
- def render_symbol_json
- render :json => {:hello => 'world'}.to_json
- end
-
- def render_json_with_render_to_string
- render :json => {:hello => render_to_string(:partial => 'partial')}
- end
-
+ # :ported:
def render_custom_code
render :text => "hello world", :status => 404
end
- def render_custom_code_rjs
- render :update, :status => 404 do |page|
- page.replace :foo, :partial => 'partial'
- end
- end
-
+ # :ported:
def render_text_with_nil
render :text => nil
end
+ # :ported:
def render_text_with_false
render :text => false
end
+ # :ported:
def render_nothing_with_appendix
render :text => "appended"
end
- def render_vanilla_js_hello
- render :js => "alert('hello')"
- end
-
+ # This test is testing 3 things:
+ # render :file in AV :ported:
+ # render :template in AC :ported:
+ # setting content type
def render_xml_hello
@name = "David"
render :template => "test/hello"
@@ -249,10 +240,6 @@ class TestController < ActionController::Base
render "test/hello"
end
- def render_xml_with_custom_content_type
- render :xml => "<blah/>", :content_type => "application/atomsvc+xml"
- end
-
def render_line_offset
render :inline => '<% raise %>', :locals => {:foo => 'bar'}
end
@@ -265,22 +252,27 @@ class TestController < ActionController::Base
# let's just rely on the template
end
+ # :ported:
def blank_response
render :text => ' '
end
+ # :ported:
def layout_test
render :action => "hello_world"
end
+ # :ported:
def builder_layout_test
render :action => "hello", :layout => "layouts/builder"
end
-
+
+ # :move: test this in ActionView
def builder_partial_test
render :action => "hello_world_container"
end
+ # :ported:
def partials_list
@test_unchanged = 'hello'
@customers = [ Customer.new("david"), Customer.new("mary") ]
@@ -306,12 +298,6 @@ class TestController < ActionController::Base
:locals => { :local_name => name }
end
- def render_implicit_html_template
- end
-
- def render_explicit_html_template
- end
-
def render_implicit_html_template_from_xhr_request
end
@@ -386,6 +372,7 @@ class TestController < ActionController::Base
render :layout => true, :inline => "Hello: <%= params[:name] %>"
end
+ # :ported:
def render_with_explicit_template
render :template => "test/hello_world"
end
@@ -394,10 +381,12 @@ class TestController < ActionController::Base
render "test/hello_world"
end
+ # :ported:
def render_with_explicit_template_with_locals
render :template => "test/render_file_with_locals", :locals => { :secret => 'area51' }
end
+ # :ported:
def double_render
render :text => "hello"
render :text => "world"
@@ -429,78 +418,24 @@ class TestController < ActionController::Base
render :action => "potential_conflicts"
end
+ # :deprecated:
+ # Tests being able to pick a .builder template over a .erb
+ # For instance, being able to have hello.xml.builder and hello.xml.erb
+ # and select one via "hello.builder" or "hello.erb"
def hello_world_from_rxml_using_action
render :action => "hello_world_from_rxml.builder"
end
+ # :deprecated:
def hello_world_from_rxml_using_template
render :template => "test/hello_world_from_rxml.builder"
end
- module RenderTestHelper
- def rjs_helper_method_from_module
- page.visual_effect :highlight
- end
- end
-
- helper RenderTestHelper
- helper do
- def rjs_helper_method(value)
- page.visual_effect :highlight, value
- end
- end
-
- def enum_rjs_test
- render :update do |page|
- page.select('.product').each do |value|
- page.rjs_helper_method_from_module
- page.rjs_helper_method(value)
- page.sortable(value, :url => { :action => "order" })
- page.draggable(value)
- end
- end
- end
-
- def delete_with_js
- @project_id = 4
- end
-
- def render_js_with_explicit_template
- @project_id = 4
- render :template => 'test/delete_with_js'
- end
-
- def render_js_with_explicit_action_template
- @project_id = 4
- render :action => 'delete_with_js'
- end
-
- def update_page
- render :update do |page|
- page.replace_html 'balance', '$37,000,000.00'
- page.visual_effect :highlight, 'balance'
- end
- end
-
- def update_page_with_instance_variables
- @money = '$37,000,000.00'
- @div_id = 'balance'
- render :update do |page|
- page.replace_html @div_id, @money
- page.visual_effect :highlight, @div_id
- end
- end
-
- def update_page_with_view_method
- render :update do |page|
- page.replace_html 'person', pluralize(2, 'person')
- end
- end
-
def action_talk_to_layout
# Action template sets variable that's picked up by layout
end
+ # :addressed:
def render_text_with_assigns
@hello = "world"
render :text => "foo"
@@ -539,25 +474,6 @@ class TestController < ActionController::Base
head :forbidden, :x_custom_header => "something"
end
- def render_with_location
- render :xml => "<hello/>", :location => "http://example.com", :status => 201
- end
-
- def render_with_object_location
- customer = Customer.new("Some guy", 1)
- render :xml => "<customer/>", :location => customer_url(customer), :status => :created
- end
-
- def render_with_to_xml
- to_xmlable = Class.new do
- def to_xml
- "<i-am-xml/>"
- end
- end.new
-
- render :xml => to_xmlable
- end
-
def render_using_layout_around_block
render :action => "using_layout_around_block"
end
@@ -574,22 +490,6 @@ class TestController < ActionController::Base
render :partial => 'partial.html.erb'
end
- def partial_as_rjs
- render :update do |page|
- page.replace :foo, :partial => 'partial'
- end
- end
-
- def respond_to_partial_as_rjs
- respond_to do |format|
- format.js do
- render :update do |page|
- page.replace :foo, :partial => 'partial'
- end
- end
- end
- end
-
def partial
render :partial => 'partial'
end
@@ -725,9 +625,7 @@ class TestController < ActionController::Base
"accessing_params_in_template_with_layout",
"render_with_explicit_template",
"render_with_explicit_string_template",
- "render_js_with_explicit_template",
- "render_js_with_explicit_action_template",
- "delete_with_js", "update_page", "update_page_with_instance_variables"
+ "update_page", "update_page_with_instance_variables"
"layouts/standard"
when "action_talk_to_layout", "layout_overriding_layout"
@@ -750,6 +648,7 @@ class RenderTest < ActionController::TestCase
@request.host = "www.nextangle.com"
end
+ # :ported:
def test_simple_show
get :hello_world
assert_response 200
@@ -758,11 +657,13 @@ class RenderTest < ActionController::TestCase
assert_equal "<html>Hello world!</html>", @response.body
end
+ # :ported:
def test_renders_default_template_for_missing_action
get :'hyphen-ated'
assert_template 'test/hyphen-ated'
end
+ # :ported:
def test_render
get :render_hello_world
assert_template "test/hello_world"
@@ -772,7 +673,7 @@ class RenderTest < ActionController::TestCase
begin
get :render_line_offset
flunk "the action should have raised an exception"
- rescue RuntimeError => exc
+ rescue StandardError => exc
line = exc.backtrace.first
assert(line =~ %r{:(\d+):})
assert_equal "1", $1,
@@ -780,129 +681,118 @@ class RenderTest < ActionController::TestCase
end
end
+ # :ported: compatibility
def test_render_with_forward_slash
get :render_hello_world_with_forward_slash
assert_template "test/hello_world"
end
+ # :ported:
def test_render_in_top_directory
get :render_template_in_top_directory
assert_template "shared"
assert_equal "Elastica", @response.body
end
+ # :ported:
def test_render_in_top_directory_with_slash
get :render_template_in_top_directory_with_slash
assert_template "shared"
assert_equal "Elastica", @response.body
end
+ # :ported:
def test_render_from_variable
get :render_hello_world_from_variable
assert_equal "hello david", @response.body
end
+ # :ported:
def test_render_action
get :render_action_hello_world
assert_template "test/hello_world"
end
+ # :ported:
def test_render_action_hello_world_as_string
get :render_action_hello_world_as_string
assert_equal "Hello world!", @response.body
assert_template "test/hello_world"
end
+ # :ported:
def test_render_action_with_symbol
get :render_action_hello_world_with_symbol
assert_template "test/hello_world"
end
+ # :ported:
def test_render_text
get :render_text_hello_world
assert_equal "hello world", @response.body
end
+ # :ported:
def test_do_with_render_text_and_layout
get :render_text_hello_world_with_layout
assert_equal "<html>hello world, I'm here!</html>", @response.body
end
+ # :ported:
def test_do_with_render_action_and_layout_false
get :hello_world_with_layout_false
assert_equal 'Hello world!', @response.body
end
+ # :ported:
def test_render_file_with_instance_variables
get :render_file_with_instance_variables
assert_equal "The secret is in the sauce\n", @response.body
end
+ # :ported:
def test_render_file_as_string_with_instance_variables
get :render_file_as_string_with_instance_variables
assert_equal "The secret is in the sauce\n", @response.body
end
+ # :ported:
def test_render_file_not_using_full_path
get :render_file_not_using_full_path
assert_equal "The secret is in the sauce\n", @response.body
end
+ # :ported:
def test_render_file_not_using_full_path_with_dot_in_path
get :render_file_not_using_full_path_with_dot_in_path
assert_equal "The secret is in the sauce\n", @response.body
end
+ # :ported:
def test_render_file_using_pathname
get :render_file_using_pathname
assert_equal "The secret is in the sauce\n", @response.body
end
+ # :ported:
def test_render_file_with_locals
get :render_file_with_locals
assert_equal "The secret is in the sauce\n", @response.body
end
+ # :ported:
def test_render_file_as_string_with_locals
get :render_file_as_string_with_locals
assert_equal "The secret is in the sauce\n", @response.body
end
+ # :assessed:
def test_render_file_from_template
get :render_file_from_template
assert_equal "The secret is in the sauce\n", @response.body
end
- def test_render_json
- get :render_json_hello_world
- assert_equal '{"hello": "world"}', @response.body
- assert_equal 'application/json', @response.content_type
- end
-
- def test_render_json_with_callback
- get :render_json_hello_world_with_callback
- assert_equal 'alert({"hello": "world"})', @response.body
- assert_equal 'application/json', @response.content_type
- end
-
- def test_render_json_with_custom_content_type
- get :render_json_with_custom_content_type
- assert_equal '{"hello": "world"}', @response.body
- assert_equal 'text/javascript', @response.content_type
- end
-
- def test_render_symbol_json
- get :render_symbol_json
- assert_equal '{"hello": "world"}', @response.body
- assert_equal 'application/json', @response.content_type
- end
-
- def test_render_json_with_render_to_string
- get :render_json_with_render_to_string
- assert_equal '{"hello": "partial html"}', @response.body
- assert_equal 'application/json', @response.content_type
- end
-
+ # :ported:
def test_render_custom_code
get :render_custom_code
assert_response 404
@@ -910,37 +800,37 @@ class RenderTest < ActionController::TestCase
assert_equal 'hello world', @response.body
end
- def test_render_custom_code_rjs
- get :render_custom_code_rjs
- assert_response 404
- assert_equal %(Element.replace("foo", "partial html");), @response.body
- end
-
+ # :ported:
def test_render_text_with_nil
get :render_text_with_nil
assert_response 200
assert_equal ' ', @response.body
end
+ # :ported:
def test_render_text_with_false
get :render_text_with_false
assert_equal 'false', @response.body
end
+ # :ported:
def test_render_nothing_with_appendix
get :render_nothing_with_appendix
assert_response 200
assert_equal 'appended', @response.body
end
+ # :ported:
def test_attempt_to_access_object_method
assert_raise(ActionController::UnknownAction, "No action responded to [clone]") { get :clone }
end
+ # :ported:
def test_private_methods
assert_raise(ActionController::UnknownAction, "No action responded to [determine_layout]") { get :determine_layout }
end
+ # :ported:
def test_access_to_request_in_view
get :accessing_request_in_template
assert_equal "Hello: www.nextangle.com", @response.body
@@ -951,58 +841,45 @@ class RenderTest < ActionController::TestCase
assert_equal "Logger", @response.body
end
+ # :ported:
def test_access_to_action_name_in_view
get :accessing_action_name_in_template
assert_equal "accessing_action_name_in_template", @response.body
end
+ # :ported:
def test_access_to_controller_name_in_view
get :accessing_controller_name_in_template
assert_equal "test", @response.body # name is explicitly set to 'test' inside the controller.
end
- def test_render_vanilla_js
- get :render_vanilla_js_hello
- assert_equal "alert('hello')", @response.body
- assert_equal "text/javascript", @response.content_type
- end
-
+ # :ported:
def test_render_xml
get :render_xml_hello
assert_equal "<html>\n <p>Hello David</p>\n<p>This is grand!</p>\n</html>\n", @response.body
assert_equal "application/xml", @response.content_type
end
+ # :ported:
def test_render_xml_as_string_template
get :render_xml_hello_as_string_template
assert_equal "<html>\n <p>Hello David</p>\n<p>This is grand!</p>\n</html>\n", @response.body
assert_equal "application/xml", @response.content_type
end
+ # :ported:
def test_render_xml_with_default
get :greeting
assert_equal "<p>This is grand!</p>\n", @response.body
end
+ # :move: test in AV
def test_render_xml_with_partial
get :builder_partial_test
assert_equal "<test>\n <hello/>\n</test>\n", @response.body
end
- def test_enum_rjs_test
- ActiveSupport::SecureRandom.stubs(:base64).returns("asdf")
- get :enum_rjs_test
- body = %{
- $$(".product").each(function(value, index) {
- new Effect.Highlight(element,{});
- new Effect.Highlight(value,{});
- Sortable.create(value, {onUpdate:function(){new Ajax.Request('/test/order', {asynchronous:true, evalScripts:true, parameters:Sortable.serialize(value) + '&authenticity_token=' + encodeURIComponent('asdf')})}});
- new Draggable(value, {});
- });
- }.gsub(/^ /, '').strip
- assert_equal body, @response.body
- end
-
+ # :ported:
def test_layout_rendering
get :layout_test
assert_equal "<html>Hello world!</html>", @response.body
@@ -1033,6 +910,7 @@ class RenderTest < ActionController::TestCase
assert_template "test/hello_world"
end
+ # :ported:
def test_nested_rendering
@controller = Fun::GamesController.new
get :hello_world
@@ -1049,29 +927,10 @@ class RenderTest < ActionController::TestCase
assert_equal "Goodbye, Local David", @response.body
end
- def test_render_in_an_rjs_template_should_pick_html_templates_when_available
- [:js, "js"].each do |format|
- assert_nothing_raised do
- get :render_implicit_html_template, :format => format
- assert_equal %(document.write("Hello world\\n");), @response.body
- end
- end
- end
-
- def test_explicitly_rendering_an_html_template_with_implicit_html_template_renders_should_be_possible_from_an_rjs_template
- [:js, "js"].each do |format|
- assert_nothing_raised do
- get :render_explicit_html_template, :format => format
- assert_equal %(document.write("Hello world\\n");), @response.body
- end
- end
- end
-
def test_should_implicitly_render_html_template_from_xhr_request
- pending do
- xhr :get, :render_implicit_html_template_from_xhr_request
- assert_equal "XHR!\nHello HTML!", @response.body
- end
+ pending
+ # xhr :get, :render_implicit_html_template_from_xhr_request
+ # assert_equal "XHR!\nHello HTML!", @response.body
end
def test_should_implicitly_render_js_template_without_layout
@@ -1086,11 +945,6 @@ class RenderTest < ActionController::TestCase
assert_equal 'formatted html erb', @response.body
end
- def test_should_render_formatted_xml_erb_template
- get :formatted_xml_erb, :format => :xml
- assert_equal '<test>passed formatted xml erb</test>', @response.body
- end
-
def test_should_render_formatted_html_erb_template
get :formatted_xml_erb
assert_equal '<test>passed formatted html erb</test>', @response.body
@@ -1102,31 +956,6 @@ class RenderTest < ActionController::TestCase
assert_equal '<test>passed formatted html erb</test>', @response.body
end
- def test_should_render_xml_but_keep_custom_content_type
- get :render_xml_with_custom_content_type
- assert_equal "application/atomsvc+xml", @response.content_type
- end
-
- def test_render_with_default_from_accept_header
- xhr :get, :greeting
- assert_equal "$(\"body\").visualEffect(\"highlight\");", @response.body
- end
-
- def test_render_rjs_with_default
- get :delete_with_js
- assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body
- end
-
- def test_render_rjs_template_explicitly
- get :render_js_with_explicit_template
- assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body
- end
-
- def test_rendering_rjs_action_explicitly
- get :render_js_with_explicit_action_template
- assert_equal %!Element.remove("person");\nnew Effect.Highlight(\"project-4\",{});!, @response.body
- end
-
def test_layout_test_with_different_layout
get :layout_test_with_different_layout
assert_equal "<html>Hello world!</html>", @response.body
@@ -1193,6 +1022,7 @@ class RenderTest < ActionController::TestCase
assert_equal "<html>Hello world!</html>", @response.body
end
+ # :ported:
def test_double_render
assert_raise(ActionController::DoubleRenderError) { get :double_render }
end
@@ -1221,38 +1051,18 @@ class RenderTest < ActionController::TestCase
assert_equal "<title>Talking to the layout</title>\nAction was here!", @response.body
end
+ # :addressed:
def test_render_text_with_assigns
get :render_text_with_assigns
assert_equal "world", assigns["hello"]
end
+ # :ported:
def test_template_with_locals
get :render_with_explicit_template_with_locals
assert_equal "The secret is area51\n", @response.body
end
- def test_update_page
- get :update_page
- assert_template nil
- assert_equal 'text/javascript; charset=utf-8', @response.headers['Content-Type']
- assert_equal 2, @response.body.split($/).length
- end
-
- def test_update_page_with_instance_variables
- get :update_page_with_instance_variables
- assert_template nil
- assert_equal 'text/javascript; charset=utf-8', @response.headers["Content-Type"]
- assert_match /balance/, @response.body
- assert_match /\$37/, @response.body
- end
-
- def test_update_page_with_view_method
- get :update_page_with_view_method
- assert_template nil
- assert_equal 'text/javascript; charset=utf-8', @response.headers["Content-Type"]
- assert_match /2 people/, @response.body
- end
-
def test_yield_content_for
assert_not_deprecated { get :yield_content_for }
assert_equal "<title>Putting stuff in the title!</title>\n\nGreat stuff!\n", @response.body
@@ -1282,15 +1092,15 @@ class RenderTest < ActionController::TestCase
def test_head_with_symbolic_status
get :head_with_symbolic_status, :status => "ok"
- assert_equal "200 OK", @response.status
+ assert_equal 200, @response.status
assert_response :ok
get :head_with_symbolic_status, :status => "not_found"
- assert_equal "404 Not Found", @response.status
+ assert_equal 404, @response.status
assert_response :not_found
get :head_with_symbolic_status, :status => "no_content"
- assert_equal "204 No Content", @response.status
+ assert_equal 204, @response.status
assert !@response.headers.include?('Content-Length')
assert_response :no_content
@@ -1311,7 +1121,7 @@ class RenderTest < ActionController::TestCase
def test_head_with_string_status
get :head_with_string_status, :status => "404 Eat Dirt"
assert_equal 404, @response.response_code
- assert_equal "Eat Dirt", @response.message
+ assert_equal "Not Found", @response.message
assert_response :not_found
end
@@ -1323,31 +1133,6 @@ class RenderTest < ActionController::TestCase
assert_response :forbidden
end
- def test_rendering_with_location_should_set_header
- get :render_with_location
- assert_equal "http://example.com", @response.headers["Location"]
- end
-
- def test_rendering_xml_should_call_to_xml_if_possible
- get :render_with_to_xml
- assert_equal "<i-am-xml/>", @response.body
- end
-
- def test_rendering_with_object_location_should_set_header_with_url_for
- ActionController::Routing::Routes.draw do |map|
- map.resources :customers
- map.connect ':controller/:action/:id'
- end
-
- get :render_with_object_location
- assert_equal "http://www.nextangle.com/customers/1", @response.headers["Location"]
- end
-
- def test_should_use_implicit_content_type
- get :implicit_content_type, :format => 'atom'
- assert_equal Mime::ATOM, @response.content_type
- end
-
def test_using_layout_around_block
get :render_using_layout_around_block
assert_equal "Before (David)\nInside from block\nAfter", @response.body
@@ -1378,26 +1163,6 @@ class RenderTest < ActionController::TestCase
assert_equal 'partial html', @response.body
end
- def test_should_render_html_formatted_partial_with_rjs
- xhr :get, :partial_as_rjs
- assert_equal %(Element.replace("foo", "partial html");), @response.body
- end
-
- def test_should_render_html_formatted_partial_with_rjs_and_js_format
- xhr :get, :respond_to_partial_as_rjs
- assert_equal %(Element.replace("foo", "partial html");), @response.body
- end
-
- def test_should_render_js_partial
- xhr :get, :partial, :format => 'js'
- assert_equal 'partial js', @response.body
- end
-
- def test_should_render_with_alternate_default_render
- xhr :get, :render_alternate_default
- assert_equal %(Element.replace("foo", "partial html");), @response.body
- end
-
def test_partial_only_with_layout
get :partial_only_with_layout
assert_equal "<html>only partial</html>", @response.body
@@ -1579,7 +1344,7 @@ class EtagRenderTest < ActionController::TestCase
def test_render_against_etag_request_should_304_when_match
@request.if_none_match = etag_for("hello david")
get :render_hello_world_from_variable
- assert_equal "304 Not Modified", @response.status
+ assert_equal 304, @response.status.to_i
assert @response.body.empty?
end
@@ -1592,13 +1357,13 @@ class EtagRenderTest < ActionController::TestCase
def test_render_against_etag_request_should_200_when_no_match
@request.if_none_match = etag_for("hello somewhere else")
get :render_hello_world_from_variable
- assert_equal "200 OK", @response.status
+ assert_equal 200, @response.status.to_i
assert !@response.body.empty?
end
def test_render_should_not_set_etag_when_last_modified_has_been_specified
get :render_hello_world_with_last_modified_set
- assert_equal "200 OK", @response.status
+ assert_equal 200, @response.status.to_i
assert_not_nil @response.last_modified
assert_nil @response.etag
assert @response.body.present?
@@ -1612,11 +1377,12 @@ class EtagRenderTest < ActionController::TestCase
@request.if_none_match = expected_etag
get :render_hello_world_from_variable
- assert_equal "304 Not Modified", @response.status
+ assert_equal 304, @response.status.to_i
+ @response = ActionController::TestResponse.new
@request.if_none_match = "\"diftag\""
get :render_hello_world_from_variable
- assert_equal "200 OK", @response.status
+ assert_equal 200, @response.status.to_i
end
def render_with_404_shouldnt_have_etag
@@ -1684,7 +1450,7 @@ class LastModifiedRenderTest < ActionController::TestCase
def test_request_not_modified
@request.if_modified_since = @last_modified
get :conditional_hello
- assert_equal "304 Not Modified", @response.status
+ assert_equal 304, @response.status.to_i
assert @response.body.blank?, @response.body
assert_equal @last_modified, @response.headers['Last-Modified']
end
@@ -1699,7 +1465,7 @@ class LastModifiedRenderTest < ActionController::TestCase
def test_request_modified
@request.if_modified_since = 'Thu, 16 Jul 2008 00:00:00 GMT'
get :conditional_hello
- assert_equal "200 OK", @response.status
+ assert_equal 200, @response.status.to_i
assert !@response.body.blank?
assert_equal @last_modified, @response.headers['Last-Modified']
end
@@ -1735,7 +1501,7 @@ class RenderingLoggingTest < ActionController::TestCase
@controller.logger = MockLogger.new
get :layout_test
logged = @controller.logger.logged.find_all {|l| l =~ /render/i }
- assert_equal "Rendering test/hello_world", logged[0]
- assert_equal "Rendering template within layouts/standard", logged[1]
+ assert logged[0] =~ %r{Rendering.*test/hello_world}
+ assert logged[1] =~ %r{Rendering template within.*layouts/standard}
end
end
diff --git a/actionpack/test/controller/render_xml_test.rb b/actionpack/test/controller/render_xml_test.rb
new file mode 100644
index 0000000000..052b4f0b52
--- /dev/null
+++ b/actionpack/test/controller/render_xml_test.rb
@@ -0,0 +1,81 @@
+require 'abstract_unit'
+require 'controller/fake_models'
+require 'pathname'
+
+class TestController < ActionController::Base
+ protect_from_forgery
+
+ def render_with_location
+ render :xml => "<hello/>", :location => "http://example.com", :status => 201
+ end
+
+ def render_with_object_location
+ customer = Customer.new("Some guy", 1)
+ render :xml => "<customer/>", :location => customer_url(customer), :status => :created
+ end
+
+ def render_with_to_xml
+ to_xmlable = Class.new do
+ def to_xml
+ "<i-am-xml/>"
+ end
+ end.new
+
+ render :xml => to_xmlable
+ end
+
+ def formatted_xml_erb
+ end
+
+ def render_xml_with_custom_content_type
+ render :xml => "<blah/>", :content_type => "application/atomsvc+xml"
+ end
+end
+
+class RenderTest < ActionController::TestCase
+ tests TestController
+
+ def setup
+ # 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)
+
+ @request.host = "www.nextangle.com"
+ end
+
+ def test_rendering_with_location_should_set_header
+ get :render_with_location
+ assert_equal "http://example.com", @response.headers["Location"]
+ end
+
+ def test_rendering_xml_should_call_to_xml_if_possible
+ get :render_with_to_xml
+ assert_equal "<i-am-xml/>", @response.body
+ end
+
+ def test_rendering_with_object_location_should_set_header_with_url_for
+ ActionController::Routing::Routes.draw do |map|
+ map.resources :customers
+ map.connect ':controller/:action/:id'
+ end
+
+ get :render_with_object_location
+ assert_equal "http://www.nextangle.com/customers/1", @response.headers["Location"]
+ end
+
+ def test_should_render_formatted_xml_erb_template
+ get :formatted_xml_erb, :format => :xml
+ assert_equal '<test>passed formatted xml erb</test>', @response.body
+ end
+
+ def test_should_render_xml_but_keep_custom_content_type
+ get :render_xml_with_custom_content_type
+ assert_equal "application/atomsvc+xml", @response.content_type
+ end
+
+ def test_should_use_implicit_content_type
+ get :implicit_content_type, :format => 'atom'
+ assert_equal Mime::ATOM, @response.content_type
+ end
+end \ No newline at end of file
diff --git a/actionpack/test/controller/request/test_request_test.rb b/actionpack/test/controller/request/test_request_test.rb
index 81551b4ba7..0a39feb7fe 100644
--- a/actionpack/test/controller/request/test_request_test.rb
+++ b/actionpack/test/controller/request/test_request_test.rb
@@ -10,26 +10,27 @@ class ActionController::TestRequestTest < ActiveSupport::TestCase
def test_test_request_has_session_options_initialized
assert @request.session_options
end
-
- Rack::Session::Abstract::ID::DEFAULT_OPTIONS.each_key do |option|
- test "test_rack_default_session_options_#{option}_exists_in_session_options_and_is_default" do
- assert_equal(Rack::Session::Abstract::ID::DEFAULT_OPTIONS[option],
- @request.session_options[option],
+
+ ActionDispatch::Session::AbstractStore::DEFAULT_OPTIONS.each_key do |option|
+ test "rack default session options #{option} exists in session options and is default" do
+ assert_equal(ActionDispatch::Session::AbstractStore::DEFAULT_OPTIONS[option],
+ @request.session_options[option],
"Missing rack session default option #{option} in request.session_options")
end
- test "test_rack_default_session_options_#{option}_exists_in_session_options" do
- assert(@request.session_options.has_key?(option),
+
+ test "rack default session options #{option} exists in session options" do
+ assert(@request.session_options.has_key?(option),
"Missing rack session option #{option} in request.session_options")
end
end
-
+
def test_session_id_exists_by_default
assert_not_nil(@request.session_options[:id])
end
-
+
def test_session_id_different_on_each_call
- prev_id =
+ prev_id =
assert_not_equal(@request.session_options[:id], ActionController::TestRequest.new.session_options[:id])
end
-
+
end \ No newline at end of file
diff --git a/actionpack/test/controller/rescue_test.rb b/actionpack/test/controller/rescue_test.rb
index 894420a910..490a4ff3b3 100644
--- a/actionpack/test/controller/rescue_test.rb
+++ b/actionpack/test/controller/rescue_test.rb
@@ -1,5 +1,19 @@
require 'abstract_unit'
+module ActionDispatch
+ class ShowExceptions
+ private
+ def public_path
+ "#{FIXTURE_LOAD_PATH}/public"
+ end
+
+ # Silence logger
+ def logger
+ nil
+ end
+ end
+end
+
class RescueController < ActionController::Base
class NotAuthorized < StandardError
end
@@ -138,213 +152,88 @@ class RescueController < ActionController::Base
end
end
-class RescueControllerTest < ActionController::TestCase
- FIXTURE_PUBLIC = "#{File.dirname(__FILE__)}/../fixtures".freeze
-
- def setup
- super
- set_all_requests_local
- populate_exception_object
- end
-
- def set_all_requests_local
- RescueController.consider_all_requests_local = true
- @request.remote_addr = '1.2.3.4'
- @request.host = 'example.com'
- end
-
- def populate_exception_object
- begin
- raise 'foo'
- rescue => @exception
- end
- end
-
- def test_rescue_exceptions_raised_by_filters
- with_rails_root FIXTURE_PUBLIC do
- with_all_requests_local false do
- get :before_filter_raises
- end
- end
+class ExceptionInheritanceRescueController < ActionController::Base
- assert_response :internal_server_error
+ class ParentException < StandardError
end
- def test_rescue_action_locally_if_all_requests_local
- @controller.expects(:local_request?).never
- @controller.expects(:rescue_action_locally).with(@exception)
- @controller.expects(:rescue_action_in_public).never
-
- with_all_requests_local do
- @controller.send :rescue_action, @exception
- end
+ class ChildException < ParentException
end
- def test_rescue_action_locally_if_remote_addr_is_localhost
- @controller.expects(:local_request?).returns(true)
- @controller.expects(:rescue_action_locally).with(@exception)
- @controller.expects(:rescue_action_in_public).never
-
- with_all_requests_local false do
- @controller.send :rescue_action, @exception
- end
+ class GrandchildException < ChildException
end
- def test_rescue_action_in_public_otherwise
- @controller.expects(:local_request?).returns(false)
- @controller.expects(:rescue_action_locally).never
- @controller.expects(:rescue_action_in_public).with(@exception)
+ rescue_from ChildException, :with => lambda { head :ok }
+ rescue_from ParentException, :with => lambda { head :created }
+ rescue_from GrandchildException, :with => lambda { head :no_content }
- with_all_requests_local false do
- @controller.send :rescue_action, @exception
- end
+ def raise_parent_exception
+ raise ParentException
end
- def test_rescue_action_in_public_with_localized_error_file
- # Change locale
- old_locale = I18n.locale
- I18n.locale = :da
-
- with_rails_root FIXTURE_PUBLIC do
- with_all_requests_local false do
- get :raises
- end
- end
-
- assert_response :internal_server_error
- body = File.read("#{FIXTURE_PUBLIC}/public/500.da.html")
- assert_equal body, @response.body
- ensure
- I18n.locale = old_locale
+ def raise_child_exception
+ raise ChildException
end
- def test_rescue_action_in_public_with_error_file
- with_rails_root FIXTURE_PUBLIC do
- with_all_requests_local false do
- get :raises
- end
- end
-
- assert_response :internal_server_error
- body = File.read("#{FIXTURE_PUBLIC}/public/500.html")
- assert_equal body, @response.body
+ def raise_grandchild_exception
+ raise GrandchildException
end
+end
- def test_rescue_action_in_public_without_error_file
- with_rails_root '/tmp' do
- with_all_requests_local false do
- get :raises
- end
- end
-
- assert_response :internal_server_error
- assert_equal ' ', @response.body
+class ExceptionInheritanceRescueControllerTest < ActionController::TestCase
+ def test_bottom_first
+ get :raise_grandchild_exception
+ assert_response :no_content
end
- def test_rescue_unknown_action_in_public_with_error_file
- with_rails_root FIXTURE_PUBLIC do
- with_all_requests_local false do
- get :foobar_doesnt_exist
- end
- end
-
- assert_response :not_found
- body = File.read("#{FIXTURE_PUBLIC}/public/404.html")
- assert_equal body, @response.body
+ def test_inheritance_works
+ get :raise_child_exception
+ assert_response :created
end
+end
- def test_rescue_unknown_action_in_public_without_error_file
- with_rails_root '/tmp' do
- with_all_requests_local false do
- get :foobar_doesnt_exist
- end
- end
-
- assert_response :not_found
- assert_equal ' ', @response.body
+class ControllerInheritanceRescueController < ExceptionInheritanceRescueController
+ class FirstExceptionInChildController < StandardError
end
- def test_rescue_missing_template_in_public
- with_rails_root FIXTURE_PUBLIC do
- with_all_requests_local true do
- get :missing_template
- end
- end
-
- assert_response :internal_server_error
- assert @response.body.include?('missing_template'), "Response should include the template name."
+ class SecondExceptionInChildController < StandardError
end
- def test_rescue_action_locally
- get :raises
- assert_response :internal_server_error
- assert_template 'diagnostics.erb'
- assert @response.body.include?('RescueController#raises'), "Response should include controller and action."
- assert @response.body.include?("don't panic"), "Response should include exception message."
- end
+ rescue_from FirstExceptionInChildController, 'SecondExceptionInChildController', :with => lambda { head :gone }
- def test_local_request_when_remote_addr_is_localhost
- @controller.expects(:request).returns(@request).at_least_once
- with_remote_addr '127.0.0.1' do
- assert @controller.send(:local_request?)
- end
+ def raise_first_exception_in_child_controller
+ raise FirstExceptionInChildController
end
- def test_local_request_when_remote_addr_isnt_locahost
- @controller.expects(:request).returns(@request)
- with_remote_addr '1.2.3.4' do
- assert !@controller.send(:local_request?)
- end
+ def raise_second_exception_in_child_controller
+ raise SecondExceptionInChildController
end
+end
- def test_rescue_responses
- responses = ActionController::Base.rescue_responses
-
- assert_equal ActionController::Rescue::DEFAULT_RESCUE_RESPONSE, responses.default
- assert_equal ActionController::Rescue::DEFAULT_RESCUE_RESPONSE, responses[Exception.new]
-
- assert_equal :not_found, responses[ActionController::RoutingError.name]
- assert_equal :not_found, responses[ActionController::UnknownAction.name]
- assert_equal :not_found, responses['ActiveRecord::RecordNotFound']
- assert_equal :conflict, responses['ActiveRecord::StaleObjectError']
- assert_equal :unprocessable_entity, responses['ActiveRecord::RecordInvalid']
- assert_equal :unprocessable_entity, responses['ActiveRecord::RecordNotSaved']
- assert_equal :method_not_allowed, responses['ActionController::MethodNotAllowed']
- assert_equal :not_implemented, responses['ActionController::NotImplemented']
+class ControllerInheritanceRescueControllerTest < ActionController::TestCase
+ def test_first_exception_in_child_controller
+ get :raise_first_exception_in_child_controller
+ assert_response :gone
end
- def test_rescue_templates
- templates = ActionController::Base.rescue_templates
-
- assert_equal ActionController::Rescue::DEFAULT_RESCUE_TEMPLATE, templates.default
- assert_equal ActionController::Rescue::DEFAULT_RESCUE_TEMPLATE, templates[Exception.new]
-
- assert_equal 'missing_template', templates[ActionView::MissingTemplate.name]
- assert_equal 'routing_error', templates[ActionController::RoutingError.name]
- assert_equal 'unknown_action', templates[ActionController::UnknownAction.name]
- assert_equal 'template_error', templates[ActionView::TemplateError.name]
+ def test_second_exception_in_child_controller
+ get :raise_second_exception_in_child_controller
+ assert_response :gone
end
- def test_not_implemented
- with_all_requests_local false do
- with_rails_public_path(".") do
- head :not_implemented
- end
- end
- assert_response :not_implemented
- assert_equal "GET, PUT", @response.headers['Allow']
+ def test_exception_in_parent_controller
+ get :raise_parent_exception
+ assert_response :created
end
+end
- def test_method_not_allowed
- with_all_requests_local false do
- with_rails_public_path(".") do
- get :method_not_allowed
- end
- end
- assert_response :method_not_allowed
- assert_equal "GET, HEAD, PUT", @response.headers['Allow']
+class ApplicationController < ActionController::Base
+ rescue_from ActionController::RoutingError do
+ render :text => 'no way'
end
+end
+class RescueControllerTest < ActionController::TestCase
def test_rescue_handler
get :not_authorized
assert_response :forbidden
@@ -399,133 +288,6 @@ class RescueControllerTest < ActionController::TestCase
get :resource_unavailable_raise_as_string
assert_equal "RescueController::ResourceUnavailableToRescueAsString", @response.body
end
-
- protected
- def with_all_requests_local(local = true)
- old_local, ActionController::Base.consider_all_requests_local =
- ActionController::Base.consider_all_requests_local, local
- yield
- ensure
- ActionController::Base.consider_all_requests_local = old_local
- end
-
- def with_remote_addr(addr)
- old_remote_addr, @request.remote_addr = @request.remote_addr, addr
- yield
- ensure
- @request.remote_addr = old_remote_addr
- end
-
- def with_rails_public_path(rails_root)
- old_rails = Object.const_get(:Rails) rescue nil
- mod = Object.const_set(:Rails, Module.new)
- (class << mod; self; end).instance_eval do
- define_method(:public_path) { "#{rails_root}/public" }
- end
- yield
- ensure
- Object.module_eval { remove_const(:Rails) } if defined?(Rails)
- Object.const_set(:Rails, old_rails) if old_rails
- end
-
- def with_rails_root(path = nil,&block)
- old_rails_root = RAILS_ROOT if defined?(RAILS_ROOT)
- if path
- silence_warnings { Object.const_set(:RAILS_ROOT, path) }
- else
- Object.remove_const(:RAILS_ROOT) rescue nil
- end
-
- with_rails_public_path(path, &block)
-
- ensure
- if old_rails_root
- silence_warnings { Object.const_set(:RAILS_ROOT, old_rails_root) }
- else
- Object.remove_const(:RAILS_ROOT) rescue nil
- end
- end
-end
-
-class ExceptionInheritanceRescueController < ActionController::Base
-
- class ParentException < StandardError
- end
-
- class ChildException < ParentException
- end
-
- class GrandchildException < ChildException
- end
-
- rescue_from ChildException, :with => lambda { head :ok }
- rescue_from ParentException, :with => lambda { head :created }
- rescue_from GrandchildException, :with => lambda { head :no_content }
-
- def raise_parent_exception
- raise ParentException
- end
-
- def raise_child_exception
- raise ChildException
- end
-
- def raise_grandchild_exception
- raise GrandchildException
- end
-end
-
-class ExceptionInheritanceRescueControllerTest < ActionController::TestCase
- def test_bottom_first
- get :raise_grandchild_exception
- assert_response :no_content
- end
-
- def test_inheritance_works
- get :raise_child_exception
- assert_response :created
- end
-end
-
-class ControllerInheritanceRescueController < ExceptionInheritanceRescueController
- class FirstExceptionInChildController < StandardError
- end
-
- class SecondExceptionInChildController < StandardError
- end
-
- rescue_from FirstExceptionInChildController, 'SecondExceptionInChildController', :with => lambda { head :gone }
-
- def raise_first_exception_in_child_controller
- raise FirstExceptionInChildController
- end
-
- def raise_second_exception_in_child_controller
- raise SecondExceptionInChildController
- end
-end
-
-class ControllerInheritanceRescueControllerTest < ActionController::TestCase
- def test_first_exception_in_child_controller
- get :raise_first_exception_in_child_controller
- assert_response :gone
- end
-
- def test_second_exception_in_child_controller
- get :raise_second_exception_in_child_controller
- assert_response :gone
- end
-
- def test_exception_in_parent_controller
- get :raise_parent_exception
- assert_response :created
- end
-end
-
-class ApplicationController < ActionController::Base
- rescue_from ActionController::RoutingError do
- render :text => 'no way'
- end
end
class RescueTest < ActionController::IntegrationTest
diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb
index c807e71cd7..30ab110ef7 100644
--- a/actionpack/test/controller/resources_test.rb
+++ b/actionpack/test/controller/resources_test.rb
@@ -120,6 +120,14 @@ class ResourcesTest < ActionController::TestCase
end
end
+ def test_irregular_id_requirements_should_get_passed_to_member_actions
+ expected_options = {:controller => 'messages', :action => 'custom', :id => '1.1.1'}
+
+ with_restful_routing(:messages, :member => {:custom => :get}, :requirements => {:id => /[0-9]\.[0-9]\.[0-9]/}) do
+ assert_recognizes(expected_options, :path => 'messages/1.1.1/custom', :method => :get)
+ end
+ end
+
def test_with_path_prefix
with_restful_routing :messages, :path_prefix => '/thread/:thread_id' do
assert_simply_restful_for :messages, :path_prefix => 'thread/5/', :options => { :thread_id => '5' }
diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb
index ef56119751..1694fc8f3e 100644
--- a/actionpack/test/controller/routing_test.rb
+++ b/actionpack/test/controller/routing_test.rb
@@ -1,5 +1,6 @@
require 'abstract_unit'
require 'controller/fake_controllers'
+require 'active_support/dependencies'
class MilestonesController < ActionController::Base
def index() head :ok end
@@ -89,6 +90,11 @@ class StaticSegmentTest < Test::Unit::TestCase
assert_equal 'Hello World', s.interpolation_chunk
end
+ def test_value_should_not_be_double_unescaped
+ s = ROUTING::StaticSegment.new('%D0%9A%D0%B0%D1%80%D1%82%D0%B0') # Карта
+ assert_equal '%D0%9A%D0%B0%D1%80%D1%82%D0%B0', s.interpolation_chunk
+ end
+
def test_regexp_chunk_should_escape_specials
s = ROUTING::StaticSegment.new('Hello*World')
assert_equal 'Hello\*World', s.regexp_chunk
@@ -1923,7 +1929,7 @@ class RouteSetTest < Test::Unit::TestCase
end
end
- request.path = "/people"
+ request.request_uri = "/people"
request.env["REQUEST_METHOD"] = "GET"
assert_nothing_raised { set.recognize(request) }
assert_equal("index", request.path_parameters[:action])
@@ -1945,7 +1951,7 @@ class RouteSetTest < Test::Unit::TestCase
}
request.recycle!
- request.path = "/people/5"
+ request.request_uri = "/people/5"
request.env["REQUEST_METHOD"] = "GET"
assert_nothing_raised { set.recognize(request) }
assert_equal("show", request.path_parameters[:action])
@@ -2047,7 +2053,7 @@ class RouteSetTest < Test::Unit::TestCase
end
end
- request.path = "/people/5"
+ request.request_uri = "/people/5"
request.env["REQUEST_METHOD"] = "GET"
assert_nothing_raised { set.recognize(request) }
assert_equal("show", request.path_parameters[:action])
@@ -2059,7 +2065,7 @@ class RouteSetTest < Test::Unit::TestCase
assert_equal("update", request.path_parameters[:action])
request.recycle!
- request.path = "/people/5.png"
+ request.request_uri = "/people/5.png"
request.env["REQUEST_METHOD"] = "GET"
assert_nothing_raised { set.recognize(request) }
assert_equal("show", request.path_parameters[:action])
diff --git a/actionpack/test/controller/selector_test.rb b/actionpack/test/controller/selector_test.rb
index 9d0613d1e2..5a5dc840b5 100644
--- a/actionpack/test/controller/selector_test.rb
+++ b/actionpack/test/controller/selector_test.rb
@@ -5,6 +5,7 @@
require 'abstract_unit'
require 'controller/fake_controllers'
+require 'action_controller/vendor/html-scanner'
class SelectorTest < Test::Unit::TestCase
#
diff --git a/actionpack/test/controller/send_file_test.rb b/actionpack/test/controller/send_file_test.rb
index 2e14a0a32c..0bc0eb2df6 100644
--- a/actionpack/test/controller/send_file_test.rb
+++ b/actionpack/test/controller/send_file_test.rb
@@ -11,12 +11,17 @@ class SendFileController < ActionController::Base
layout "layouts/standard" # to make sure layouts don't interfere
attr_writer :options
- def options() @options ||= {} end
+ def options
+ @options ||= {}
+ end
- def file() send_file(file_path, options) end
- def data() send_data(file_data, options) end
+ def file
+ send_file(file_path, options)
+ end
- def rescue_action(e) raise end
+ def data
+ send_data(file_data, options)
+ end
end
class SendFileTest < ActionController::TestCase
@@ -40,17 +45,19 @@ class SendFileTest < ActionController::TestCase
assert_equal file_data, response.body
end
- def test_file_stream
- response = nil
- assert_nothing_raised { response = process('file') }
- assert_not_nil response
- assert_kind_of Proc, response.body_parts
-
- require 'stringio'
- output = StringIO.new
- output.binmode
- assert_nothing_raised { response.body_parts.call(response, output) }
- assert_equal file_data, output.string
+ for_tag(:old_base) do
+ def test_file_stream
+ response = nil
+ assert_nothing_raised { response = process('file') }
+ assert_not_nil response
+ assert_kind_of Array, response.body_parts
+
+ require 'stringio'
+ output = StringIO.new
+ output.binmode
+ assert_nothing_raised { response.body_parts.each { |part| output << part.to_s } }
+ assert_equal file_data, output.string
+ end
end
def test_file_url_based_filename
@@ -149,13 +156,13 @@ class SendFileTest < ActionController::TestCase
define_method "test_send_#{method}_status" do
@controller.options = { :stream => false, :status => 500 }
assert_nothing_raised { assert_not_nil process(method) }
- assert_equal '500 Internal Server Error', @response.status
+ assert_equal 500, @response.status
end
define_method "test_default_send_#{method}_status" do
@controller.options = { :stream => false }
assert_nothing_raised { assert_not_nil process(method) }
- assert_equal ActionController::DEFAULT_RENDER_STATUS_CODE, @response.status
+ assert_equal 200, @response.status
end
end
end
diff --git a/actionpack/test/controller/test_test.rb b/actionpack/test/controller/test_test.rb
index 124e259ef6..9e88188b9a 100644
--- a/actionpack/test/controller/test_test.rb
+++ b/actionpack/test/controller/test_test.rb
@@ -184,12 +184,6 @@ XML
assert_equal Hash.new, @controller.session.to_hash
end
- def test_session_is_cleared_from_response_after_reset_session
- process :set_session
- process :reset_the_session
- assert_equal Hash.new, @response.session.to_hash
- end
-
def test_session_is_cleared_from_request_after_reset_session
process :set_session
process :reset_the_session
@@ -207,7 +201,7 @@ XML
end
def test_process_with_request_uri_with_params_with_explicit_uri
- @request.set_REQUEST_URI "/explicit/uri"
+ @request.request_uri = "/explicit/uri"
process :test_uri, :id => 7
assert_equal "/explicit/uri", @response.body
end
@@ -218,7 +212,7 @@ XML
end
def test_process_with_query_string_with_explicit_uri
- @request.set_REQUEST_URI "/explicit/uri?q=test?extra=question"
+ @request.request_uri = "/explicit/uri?q=test?extra=question"
process :test_query_string
assert_equal "q=test?extra=question", @response.body
end
@@ -620,7 +614,9 @@ XML
def test_binary_content_works_with_send_file
get :test_send_file
- assert_nothing_raised(NoMethodError) { @response.binary_content }
+ assert_deprecated do
+ assert_nothing_raised(NoMethodError) { @response.binary_content }
+ end
end
protected
@@ -635,33 +631,6 @@ XML
end
end
-class CleanBacktraceTest < ActionController::TestCase
- def test_should_reraise_the_same_object
- exception = ActiveSupport::TestCase::Assertion.new('message')
- clean_backtrace { raise exception }
- rescue Exception => caught
- assert_equal exception.object_id, caught.object_id
- assert_equal exception.message, caught.message
- end
-
- def test_should_clean_assertion_lines_from_backtrace
- path = File.expand_path("#{File.dirname(__FILE__)}/../../lib/action_controller/testing")
- exception = ActiveSupport::TestCase::Assertion.new('message')
- exception.set_backtrace ["#{path}/abc", "#{path}/assertions/def"]
- clean_backtrace { raise exception }
- rescue Exception => caught
- assert_equal ["#{path}/abc"], caught.backtrace
- end
-
- def test_should_only_clean_assertion_failure_errors
- clean_backtrace do
- raise "can't touch this", [File.expand_path("#{File.dirname(__FILE__)}/../../lib/action_controller/assertions/abc")]
- end
- rescue => caught
- assert !caught.backtrace.empty?
- end
-end
-
class InferringClassNameTest < ActionController::TestCase
def test_determine_controller_class
assert_equal ContentController, determine_class("ContentControllerTest")
diff --git a/actionpack/test/controller/verification_test.rb b/actionpack/test/controller/verification_test.rb
index 418a81baa8..d568030e41 100644
--- a/actionpack/test/controller/verification_test.rb
+++ b/actionpack/test/controller/verification_test.rb
@@ -103,17 +103,15 @@ class VerificationTest < ActionController::TestCase
end
protected
- def rescue_action(e) raise end
- def unconditional_redirect
- redirect_to :action => "unguarded"
- end
+ def unconditional_redirect
+ redirect_to :action => "unguarded"
+ end
end
- def setup
- @controller = TestController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
+ tests TestController
+
+ setup do
ActionController::Routing::Routes.add_named_route :foo, '/foo', :controller => 'test', :action => 'foo'
end
@@ -184,7 +182,7 @@ class VerificationTest < ActionController::TestCase
def test_unguarded_without_params
get :unguarded
- assert_equal "", @response.body
+ assert @response.body.blank?
end
def test_guarded_in_session_with_prereqs
diff --git a/actionpack/test/controller/view_paths_test.rb b/actionpack/test/controller/view_paths_test.rb
index 1539f8f506..c732d1c910 100644
--- a/actionpack/test/controller/view_paths_test.rb
+++ b/actionpack/test/controller/view_paths_test.rb
@@ -20,9 +20,9 @@ class ViewLoadPathsTest < ActionController::TestCase
layout 'test/sub'
def hello_world; render(:template => 'test/hello_world'); end
end
-
+
def setup
- TestController.view_paths = nil
+ # TestController.view_paths = nil
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
@@ -42,30 +42,39 @@ class ViewLoadPathsTest < ActionController::TestCase
ActiveSupport::Deprecation.behavior = @old_behavior
end
+ def expand(array)
+ array.map {|x| File.expand_path(x)}
+ end
+
+ def assert_paths(*paths)
+ controller = paths.first.is_a?(Class) ? paths.shift : @controller
+ assert_equal expand(paths), controller.view_paths.map { |p| p.to_s }
+ end
+
def test_template_load_path_was_set_correctly
- assert_equal [FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
+ assert_paths FIXTURE_LOAD_PATH
end
def test_controller_appends_view_path_correctly
@controller.append_view_path 'foo'
- assert_equal [FIXTURE_LOAD_PATH, 'foo'], @controller.view_paths.map(&:to_s)
+ assert_paths(FIXTURE_LOAD_PATH, "foo")
@controller.append_view_path(%w(bar baz))
- assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz'], @controller.view_paths.map(&:to_s)
-
+ assert_paths(FIXTURE_LOAD_PATH, "foo", "bar", "baz")
+
@controller.append_view_path(FIXTURE_LOAD_PATH)
- assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
+ assert_paths(FIXTURE_LOAD_PATH, "foo", "bar", "baz", FIXTURE_LOAD_PATH)
end
def test_controller_prepends_view_path_correctly
@controller.prepend_view_path 'baz'
- assert_equal ['baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
+ assert_paths("baz", FIXTURE_LOAD_PATH)
@controller.prepend_view_path(%w(foo bar))
- assert_equal ['foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
+ assert_paths "foo", "bar", "baz", FIXTURE_LOAD_PATH
@controller.prepend_view_path(FIXTURE_LOAD_PATH)
- assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
+ assert_paths FIXTURE_LOAD_PATH, "foo", "bar", "baz", FIXTURE_LOAD_PATH
end
def test_template_appends_view_path_correctly
@@ -73,11 +82,11 @@ class ViewLoadPathsTest < ActionController::TestCase
class_view_paths = TestController.view_paths
@controller.append_view_path 'foo'
- assert_equal [FIXTURE_LOAD_PATH, 'foo'], @controller.view_paths.map(&:to_s)
+ assert_paths FIXTURE_LOAD_PATH, "foo"
@controller.append_view_path(%w(bar baz))
- assert_equal [FIXTURE_LOAD_PATH, 'foo', 'bar', 'baz'], @controller.view_paths.map(&:to_s)
- assert_equal class_view_paths, TestController.view_paths
+ assert_paths FIXTURE_LOAD_PATH, "foo", "bar", "baz"
+ assert_paths TestController, *class_view_paths
end
def test_template_prepends_view_path_correctly
@@ -85,11 +94,11 @@ class ViewLoadPathsTest < ActionController::TestCase
class_view_paths = TestController.view_paths
@controller.prepend_view_path 'baz'
- assert_equal ['baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
+ assert_paths "baz", FIXTURE_LOAD_PATH
@controller.prepend_view_path(%w(foo bar))
- assert_equal ['foo', 'bar', 'baz', FIXTURE_LOAD_PATH], @controller.view_paths.map(&:to_s)
- assert_equal class_view_paths, TestController.view_paths
+ assert_paths "foo", "bar", "baz", FIXTURE_LOAD_PATH
+ assert_paths TestController, *class_view_paths
end
def test_view_paths
@@ -130,12 +139,12 @@ class ViewLoadPathsTest < ActionController::TestCase
A.view_paths = ['a/path']
- assert_equal ['a/path'], A.view_paths.map(&:to_s)
- assert_equal A.view_paths, B.view_paths
- assert_equal original_load_paths, C.view_paths
-
+ assert_paths A, "a/path"
+ assert_paths A, *B.view_paths
+ assert_paths C, *original_load_paths
+
C.view_paths = []
assert_nothing_raised { C.view_paths << 'c/path' }
- assert_equal ['c/path'], C.view_paths.map(&:to_s)
+ assert_paths C, "c/path"
end
end
diff --git a/actionpack/test/controller/webservice_test.rb b/actionpack/test/controller/webservice_test.rb
index e89d6bb960..9bf8da7276 100644
--- a/actionpack/test/controller/webservice_test.rb
+++ b/actionpack/test/controller/webservice_test.rb
@@ -34,7 +34,7 @@ class WebServiceTest < ActionController::IntegrationTest
def test_check_parameters
with_test_route_set do
get "/"
- assert_equal '', @controller.response.body
+ assert @controller.response.body.blank?
end
end
@@ -163,7 +163,7 @@ class WebServiceTest < ActionController::IntegrationTest
with_test_route_set do
ActionController::Base.param_parsers[Mime::XML] = :xml_simple
assert_nothing_raised { post "/", "", {'CONTENT_TYPE' => 'application/xml'} }
- assert_equal "", @controller.response.body
+ assert @controller.response.body.blank?
end
end
diff --git a/actionpack/test/dispatch/rack_test.rb b/actionpack/test/dispatch/rack_test.rb
index 9fad4b22ee..94eba2a24f 100644
--- a/actionpack/test/dispatch/rack_test.rb
+++ b/actionpack/test/dispatch/rack_test.rb
@@ -201,93 +201,3 @@ class RackRequestNeedsRewoundTest < BaseRackTest
assert_equal 0, request.body.pos
end
end
-
-class RackResponseTest < BaseRackTest
- def setup
- super
- @response = ActionDispatch::Response.new
- end
-
- test "simple output" do
- @response.body = "Hello, World!"
- @response.prepare!
-
- status, headers, body = @response.to_a
- assert_equal 200, status
- assert_equal({
- "Content-Type" => "text/html; charset=utf-8",
- "Cache-Control" => "private, max-age=0, must-revalidate",
- "ETag" => '"65a8e27d8879283831b664bd8b7f0ad4"',
- "Set-Cookie" => "",
- "Content-Length" => "13"
- }, headers)
-
- parts = []
- body.each { |part| parts << part }
- assert_equal ["Hello, World!"], parts
- end
-
- def test_utf8_output
- @response.body = [1090, 1077, 1089, 1090].pack("U*")
- @response.prepare!
-
- status, headers, body = @response.to_a
- assert_equal 200, status
- assert_equal({
- "Content-Type" => "text/html; charset=utf-8",
- "Cache-Control" => "private, max-age=0, must-revalidate",
- "ETag" => '"ebb5e89e8a94e9dd22abf5d915d112b2"',
- "Set-Cookie" => "",
- "Content-Length" => "8"
- }, headers)
- end
-
- def test_streaming_block
- @response.body = Proc.new do |response, output|
- 5.times { |n| output.write(n) }
- end
- @response.prepare!
-
- status, headers, body = @response.to_a
- assert_equal 200, status
- assert_equal({
- "Content-Type" => "text/html; charset=utf-8",
- "Cache-Control" => "no-cache",
- "Set-Cookie" => ""
- }, headers)
-
- parts = []
- body.each { |part| parts << part.to_s }
- assert_equal ["0", "1", "2", "3", "4"], parts
- end
-end
-
-class RackResponseHeadersTest < BaseRackTest
- def setup
- super
- @response = ActionDispatch::Response.new
- @response.status = "200 OK"
- end
-
- test "content type" do
- [204, 304].each do |c|
- @response.status = c.to_s
- assert !response_headers.has_key?("Content-Type"), "#{c} should not have Content-Type header"
- end
-
- [200, 302, 404, 500].each do |c|
- @response.status = c.to_s
- assert response_headers.has_key?("Content-Type"), "#{c} did not have Content-Type header"
- end
- end
-
- test "status" do
- assert !response_headers.has_key?('Status')
- end
-
- private
- def response_headers
- @response.prepare!
- @response.to_a[1]
- end
-end
diff --git a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
index 88b81dc493..9e008a9ae8 100644
--- a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
@@ -94,9 +94,8 @@ class MultipartParamsParsingTest < ActionController::IntegrationTest
assert_equal %w(files foo), params.keys.sort
assert_equal 'bar', params['foo']
- # Ruby CGI doesn't handle multipart/mixed for us.
+ # Rack doesn't handle multipart/mixed for us.
files = params['files']
- assert_kind_of String, files
files.force_encoding('ASCII-8BIT') if files.respond_to?(:force_encoding)
assert_equal 19756, files.size
end
@@ -133,46 +132,6 @@ class MultipartParamsParsingTest < ActionController::IntegrationTest
end
end
- # The lint wrapper is used in integration tests
- # instead of a normal StringIO class
- InputWrapper = Rack::Lint::InputWrapper
-
- test "parses unwindable stream" do
- InputWrapper.any_instance.stubs(:rewind).raises(Errno::ESPIPE)
- params = parse_multipart('large_text_file')
- assert_equal %w(file foo), params.keys.sort
- assert_equal 'bar', params['foo']
- end
-
- test "uploads and reads file with unwindable input" do
- InputWrapper.any_instance.stubs(:rewind).raises(Errno::ESPIPE)
-
- with_test_routing do
- post '/read', :uploaded_data => fixture_file_upload(FIXTURE_PATH + "/hello.txt", "text/plain")
- assert_equal "File: Hello", response.body
- end
- end
-
- test "passes through rack middleware and uploads file" do
- with_muck_middleware do
- with_test_routing do
- post '/read', :uploaded_data => fixture_file_upload(FIXTURE_PATH + "/hello.txt", "text/plain")
- assert_equal "File: Hello", response.body
- end
- end
- end
-
- test "passes through rack middleware and uploads file with unwindable input" do
- InputWrapper.any_instance.stubs(:rewind).raises(Errno::ESPIPE)
-
- with_muck_middleware do
- with_test_routing do
- post '/read', :uploaded_data => fixture_file_upload(FIXTURE_PATH + "/hello.txt", "text/plain")
- assert_equal "File: Hello", response.body
- end
- end
- end
-
private
def fixture(name)
File.open(File.join(FIXTURE_PATH, name), 'rb') do |file|
@@ -199,25 +158,4 @@ class MultipartParamsParsingTest < ActionController::IntegrationTest
yield
end
end
-
- class MuckMiddleware
- def initialize(app)
- @app = app
- end
-
- def call(env)
- env['rack.input'].read
- env['rack.input'].rewind
- @app.call(env)
- end
- end
-
- def with_muck_middleware
- original_middleware = ActionController::Dispatcher.middleware
- middleware = original_middleware.dup
- middleware.insert_after ActionDispatch::RewindableInput, MuckMiddleware
- ActionController::Dispatcher.middleware = middleware
- yield
- ActionController::Dispatcher.middleware = original_middleware
- end
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 8de4a83d76..7167cdafac 100644
--- a/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/url_encoded_params_parsing_test.rb
@@ -126,45 +126,7 @@ class UrlEncodedParamsParsingTest < ActionController::IntegrationTest
assert_parses expected, query
end
- test "passes through rack middleware and parses params" do
- with_muck_middleware do
- assert_parses({ "a" => { "b" => "c" } }, "a[b]=c")
- end
- end
-
- # The lint wrapper is used in integration tests
- # instead of a normal StringIO class
- InputWrapper = Rack::Lint::InputWrapper
-
- test "passes through rack middleware and parses params with unwindable input" do
- InputWrapper.any_instance.stubs(:rewind).raises(Errno::ESPIPE)
- with_muck_middleware do
- assert_parses({ "a" => { "b" => "c" } }, "a[b]=c")
- end
- end
-
private
- class MuckMiddleware
- def initialize(app)
- @app = app
- end
-
- def call(env)
- env['rack.input'].read
- env['rack.input'].rewind
- @app.call(env)
- end
- end
-
- def with_muck_middleware
- original_middleware = ActionController::Dispatcher.middleware
- middleware = original_middleware.dup
- middleware.insert_after ActionDispatch::RewindableInput, MuckMiddleware
- ActionController::Dispatcher.middleware = middleware
- yield
- ActionController::Dispatcher.middleware = original_middleware
- end
-
def with_test_routing
with_routing do |set|
set.draw do |map|
diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb
index d57a2a611f..3a85db8aa5 100644
--- a/actionpack/test/dispatch/request_test.rb
+++ b/actionpack/test/dispatch/request_test.rb
@@ -307,7 +307,7 @@ class RequestTest < ActiveSupport::TestCase
test "restrict method hacking" do
[:get, :put, :delete].each do |method|
request = stub_request 'REQUEST_METHOD' => method.to_s.upcase,
- 'action_controller.request.request_parameters' => { :_method => 'put' }
+ 'action_dispatch.request.request_parameters' => { :_method => 'put' }
assert_equal method, request.method
end
end
diff --git a/actionpack/test/dispatch/response_test.rb b/actionpack/test/dispatch/response_test.rb
new file mode 100644
index 0000000000..2ddc6cb2b5
--- /dev/null
+++ b/actionpack/test/dispatch/response_test.rb
@@ -0,0 +1,130 @@
+require 'abstract_unit'
+
+class ResponseTest < ActiveSupport::TestCase
+ def setup
+ @response = ActionDispatch::Response.new
+ end
+
+ test "simple output" do
+ @response.body = "Hello, World!"
+ @response.prepare!
+
+ status, headers, body = @response.to_a
+ assert_equal 200, status
+ assert_equal({
+ "Content-Type" => "text/html; charset=utf-8",
+ "Cache-Control" => "private, max-age=0, must-revalidate",
+ "ETag" => '"65a8e27d8879283831b664bd8b7f0ad4"',
+ "Set-Cookie" => "",
+ "Content-Length" => "13"
+ }, headers)
+
+ parts = []
+ body.each { |part| parts << part }
+ assert_equal ["Hello, World!"], parts
+ end
+
+ test "utf8 output" do
+ @response.body = [1090, 1077, 1089, 1090].pack("U*")
+ @response.prepare!
+
+ status, headers, body = @response.to_a
+ assert_equal 200, status
+ assert_equal({
+ "Content-Type" => "text/html; charset=utf-8",
+ "Cache-Control" => "private, max-age=0, must-revalidate",
+ "ETag" => '"ebb5e89e8a94e9dd22abf5d915d112b2"',
+ "Set-Cookie" => "",
+ "Content-Length" => "8"
+ }, headers)
+ end
+
+ test "streaming block" do
+ @response.body = Proc.new do |response, output|
+ 5.times { |n| output.write(n) }
+ end
+ @response.prepare!
+
+ status, headers, body = @response.to_a
+ assert_equal 200, status
+ assert_equal({
+ "Content-Type" => "text/html; charset=utf-8",
+ "Cache-Control" => "no-cache",
+ "Set-Cookie" => ""
+ }, headers)
+
+ parts = []
+ body.each { |part| parts << part.to_s }
+ assert_equal ["0", "1", "2", "3", "4"], parts
+ end
+
+ test "content type" do
+ [204, 304].each do |c|
+ @response.status = c.to_s
+ @response.prepare!
+ status, headers, body = @response.to_a
+ assert !headers.has_key?("Content-Type"), "#{c} should not have Content-Type header"
+ end
+
+ [200, 302, 404, 500].each do |c|
+ @response.status = c.to_s
+ @response.prepare!
+ status, headers, body = @response.to_a
+ assert headers.has_key?("Content-Type"), "#{c} did not have Content-Type header"
+ end
+ end
+
+ test "does not include Status header" do
+ @response.status = "200 OK"
+ @response.prepare!
+ status, headers, body = @response.to_a
+ assert !headers.has_key?('Status')
+ end
+
+ test "response code" do
+ @response.status = "200 OK"
+ assert_equal 200, @response.response_code
+
+ @response.status = "200"
+ assert_equal 200, @response.response_code
+
+ @response.status = 200
+ assert_equal 200, @response.response_code
+ end
+
+ test "code" do
+ @response.status = "200 OK"
+ assert_equal "200", @response.code
+
+ @response.status = "200"
+ assert_equal "200", @response.code
+
+ @response.status = 200
+ assert_equal "200", @response.code
+ end
+
+ test "message" do
+ @response.status = "200 OK"
+ assert_equal "OK", @response.message
+
+ @response.status = "200"
+ assert_equal "OK", @response.message
+
+ @response.status = 200
+ assert_equal "OK", @response.message
+ end
+
+ test "cookies" do
+ @response.set_cookie("user_name", :value => "david", :path => "/")
+ @response.prepare!
+ status, headers, body = @response.to_a
+ assert_equal "user_name=david; path=/", headers["Set-Cookie"]
+ assert_equal({"user_name" => "david"}, @response.cookies)
+
+ @response.set_cookie("login", :value => "foo&bar", :path => "/", :expires => Time.utc(2005, 10, 10,5))
+ @response.prepare!
+ status, headers, body = @response.to_a
+ assert_equal "user_name=david; path=/\nlogin=foo%26bar; path=/; expires=Mon, 10-Oct-2005 05:00:00 GMT", headers["Set-Cookie"]
+ assert_equal({"login" => "foo&bar", "user_name" => "david"}, @response.cookies)
+ end
+end
diff --git a/actionpack/test/dispatch/session/cookie_store_test.rb b/actionpack/test/dispatch/session/cookie_store_test.rb
index b9bf8cf411..2db76818ac 100644
--- a/actionpack/test/dispatch/session/cookie_store_test.rb
+++ b/actionpack/test/dispatch/session/cookie_store_test.rb
@@ -5,13 +5,15 @@ class CookieStoreTest < ActionController::IntegrationTest
SessionKey = '_myapp_session'
SessionSecret = 'b3c631c314c0bbca50c1b2843150fe33'
+ # Make sure Session middleware doesnt get included in the middleware stack
+ ActionController::Base.session_store = nil
+
DispatcherApp = ActionController::Dispatcher.new
CookieStoreApp = ActionDispatch::Session::CookieStore.new(DispatcherApp,
:key => SessionKey, :secret => SessionSecret)
Verifier = ActiveSupport::MessageVerifier.new(SessionSecret, 'SHA1')
-
- SignedBar = "BAh7BjoIZm9vIghiYXI%3D--fef868465920f415f2c0652d6910d3af288a0367"
+ SignedBar = Verifier.generate(:foo => "bar", :session_id => ActiveSupport::SecureRandom.hex(16))
class TestController < ActionController::Base
def no_session_access
diff --git a/actionpack/test/dispatch/session/mem_cache_store_test.rb b/actionpack/test/dispatch/session/mem_cache_store_test.rb
index 7561c93e4a..278f2c83ea 100644
--- a/actionpack/test/dispatch/session/mem_cache_store_test.rb
+++ b/actionpack/test/dispatch/session/mem_cache_store_test.rb
@@ -61,6 +61,14 @@ class MemCacheStoreTest < ActionController::IntegrationTest
end
end
+ def test_getting_session_value_does_not_set_cookie
+ with_test_route_set do
+ get '/get_session_value'
+ assert_response :success
+ assert_equal "", headers["Set-Cookie"]
+ end
+ end
+
def test_setting_session_value_after_session_reset
with_test_route_set do
get '/set_session_value'
diff --git a/actionpack/test/dispatch/session/test_session_test.rb b/actionpack/test/dispatch/session/test_session_test.rb
index de6539e1cc..0ff93f1c5d 100644
--- a/actionpack/test/dispatch/session/test_session_test.rb
+++ b/actionpack/test/dispatch/session/test_session_test.rb
@@ -2,37 +2,30 @@ require 'abstract_unit'
require 'stringio'
class ActionController::TestSessionTest < ActiveSupport::TestCase
-
def test_calling_delete_without_parameters_raises_deprecation_warning_and_calls_to_clear_test_session
assert_deprecated(/use clear instead/){ ActionController::TestSession.new.delete }
end
-
+
def test_calling_update_without_parameters_raises_deprecation_warning_and_calls_to_clear_test_session
assert_deprecated(/use replace instead/){ ActionController::TestSession.new.update }
end
-
+
def test_calling_close_raises_deprecation_warning
assert_deprecated(/sessions should no longer be closed/){ ActionController::TestSession.new.close }
end
-
- def test_defaults
- session = ActionController::TestSession.new
- assert_equal({}, session.data)
- assert_equal('', session.session_id)
- end
-
+
def test_ctor_allows_setting
session = ActionController::TestSession.new({:one => 'one', :two => 'two'})
assert_equal('one', session[:one])
assert_equal('two', session[:two])
end
-
+
def test_setting_session_item_sets_item
session = ActionController::TestSession.new
session[:key] = 'value'
assert_equal('value', session[:key])
end
-
+
def test_calling_delete_removes_item
session = ActionController::TestSession.new
session[:key] = 'value'
@@ -40,13 +33,13 @@ class ActionController::TestSessionTest < ActiveSupport::TestCase
session.delete(:key)
assert_nil(session[:key])
end
-
+
def test_calling_update_with_params_passes_to_attributes
session = ActionController::TestSession.new()
session.update('key' => 'value')
assert_equal('value', session[:key])
end
-
+
def test_clear_emptys_session
params = {:one => 'one', :two => 'two'}
session = ActionController::TestSession.new({:one => 'one', :two => 'two'})
@@ -54,5 +47,4 @@ class ActionController::TestSessionTest < ActiveSupport::TestCase
assert_nil(session[:one])
assert_nil(session[:two])
end
-
-end \ No newline at end of file
+end
diff --git a/actionpack/test/dispatch/show_exceptions_test.rb b/actionpack/test/dispatch/show_exceptions_test.rb
new file mode 100644
index 0000000000..ce1973853e
--- /dev/null
+++ b/actionpack/test/dispatch/show_exceptions_test.rb
@@ -0,0 +1,108 @@
+require 'abstract_unit'
+
+module ActionDispatch
+ class ShowExceptions
+ private
+ def public_path
+ "#{FIXTURE_LOAD_PATH}/public"
+ end
+
+ # Silence logger
+ def logger
+ nil
+ end
+ end
+end
+
+class ShowExceptionsTest < ActionController::IntegrationTest
+ Boomer = lambda do |env|
+ req = ActionDispatch::Request.new(env)
+ case req.path
+ when "/not_found"
+ raise ActionController::UnknownAction
+ when "/method_not_allowed"
+ raise ActionController::MethodNotAllowed
+ when "/not_implemented"
+ raise ActionController::NotImplemented
+ when "/unprocessable_entity"
+ raise ActionController::InvalidAuthenticityToken
+ else
+ raise "puke!"
+ end
+ end
+
+ ProductionApp = ActionDispatch::ShowExceptions.new(Boomer, false)
+ DevelopmentApp = ActionDispatch::ShowExceptions.new(Boomer, true)
+
+ test "rescue in public from a remote ip" do
+ @integration_session = open_session(ProductionApp)
+ self.remote_addr = '208.77.188.166'
+
+ get "/"
+ assert_response 500
+ assert_equal "500 error fixture\n", body
+
+ get "/not_found"
+ assert_response 404
+ assert_equal "404 error fixture\n", body
+
+ get "/method_not_allowed"
+ assert_response 405
+ assert_equal "", body
+ end
+
+ test "rescue locally from a local request" do
+ @integration_session = open_session(ProductionApp)
+ self.remote_addr = '127.0.0.1'
+
+ get "/"
+ assert_response 500
+ assert_match /puke/, body
+
+ get "/not_found"
+ assert_response 404
+ assert_match /#{ActionController::UnknownAction.name}/, body
+
+ get "/method_not_allowed"
+ assert_response 405
+ assert_match /ActionController::MethodNotAllowed/, body
+ end
+
+ test "localize public rescue message" do
+ # Change locale
+ old_locale = I18n.locale
+ I18n.locale = :da
+
+ begin
+ @integration_session = open_session(ProductionApp)
+ self.remote_addr = '208.77.188.166'
+
+ get "/"
+ assert_response 500
+ assert_equal "500 localized error fixture\n", body
+
+ get "/not_found"
+ assert_response 404
+ assert_equal "404 error fixture\n", body
+ ensure
+ I18n.locale = old_locale
+ end
+ end
+
+ test "always rescue locally in development mode" do
+ @integration_session = open_session(DevelopmentApp)
+ self.remote_addr = '208.77.188.166'
+
+ get "/"
+ assert_response 500
+ assert_match /puke/, body
+
+ get "/not_found"
+ assert_response 404
+ assert_match /#{ActionController::UnknownAction.name}/, body
+
+ get "/method_not_allowed"
+ assert_response 405
+ assert_match /ActionController::MethodNotAllowed/, body
+ end
+end
diff --git a/actionpack/test/dispatch/test_request_test.rb b/actionpack/test/dispatch/test_request_test.rb
new file mode 100644
index 0000000000..5da02b2ea6
--- /dev/null
+++ b/actionpack/test/dispatch/test_request_test.rb
@@ -0,0 +1,45 @@
+require 'abstract_unit'
+
+class TestRequestTest < ActiveSupport::TestCase
+ test "sane defaults" do
+ env = ActionDispatch::TestRequest.new.env
+
+ assert_equal "GET", env.delete("REQUEST_METHOD")
+ assert_equal "off", env.delete("HTTPS")
+ assert_equal "http", env.delete("rack.url_scheme")
+ assert_equal "example.org", env.delete("SERVER_NAME")
+ assert_equal "80", env.delete("SERVER_PORT")
+ assert_equal "/", env.delete("PATH_INFO")
+ assert_equal "", env.delete("SCRIPT_NAME")
+ assert_equal "", env.delete("QUERY_STRING")
+ assert_equal "0", env.delete("CONTENT_LENGTH")
+
+ assert_equal "test.host", env.delete("HTTP_HOST")
+ assert_equal "0.0.0.0", env.delete("REMOTE_ADDR")
+ assert_equal "Rails Testing", env.delete("HTTP_USER_AGENT")
+
+ assert_equal [1, 0], env.delete("rack.version")
+ assert_equal "", env.delete("rack.input").string
+ assert_kind_of StringIO, env.delete("rack.errors")
+ assert_equal true, env.delete("rack.multithread")
+ assert_equal true, env.delete("rack.multiprocess")
+ assert_equal false, env.delete("rack.run_once")
+
+ assert env.empty?, env.inspect
+ end
+
+ test "cookie jar" do
+ req = ActionDispatch::TestRequest.new
+
+ assert_equal({}, req.cookies)
+ assert_equal nil, req.env["HTTP_COOKIE"]
+
+ req.cookies["user_name"] = "david"
+ assert_equal({"user_name" => "david"}, req.cookies)
+ assert_equal "user_name=david;", req.env["HTTP_COOKIE"]
+
+ req.cookies["login"] = "XJ-122"
+ assert_equal({"user_name" => "david", "login" => "XJ-122"}, req.cookies)
+ assert_equal %w(login=XJ-122 user_name=david), req.env["HTTP_COOKIE"].split(/; ?/).sort
+ end
+end
diff --git a/actionpack/test/fixtures/layout_tests/layouts/third_party_template_library.mab b/actionpack/test/fixtures/layout_tests/layouts/third_party_template_library.mab
index 018abfb0ac..fcee620d82 100644
--- a/actionpack/test/fixtures/layout_tests/layouts/third_party_template_library.mab
+++ b/actionpack/test/fixtures/layout_tests/layouts/third_party_template_library.mab
@@ -1 +1 @@
-Mab \ No newline at end of file
+layouts/third_party_template_library.mab \ No newline at end of file
diff --git a/actionpack/test/fixtures/layouts/standard.erb b/actionpack/test/fixtures/layouts/standard.html.erb
index 368764e6f4..368764e6f4 100644
--- a/actionpack/test/fixtures/layouts/standard.erb
+++ b/actionpack/test/fixtures/layouts/standard.html.erb
diff --git a/actionpack/test/fixtures/test/greeting.erb b/actionpack/test/fixtures/test/greeting.html.erb
index 62fb0293f0..62fb0293f0 100644
--- a/actionpack/test/fixtures/test/greeting.erb
+++ b/actionpack/test/fixtures/test/greeting.html.erb
diff --git a/actionpack/test/fixtures/test/render_file_with_locals_and_default.erb b/actionpack/test/fixtures/test/render_file_with_locals_and_default.erb
new file mode 100644
index 0000000000..9b4900acc5
--- /dev/null
+++ b/actionpack/test/fixtures/test/render_file_with_locals_and_default.erb
@@ -0,0 +1 @@
+<%= secret ||= 'one' %> \ No newline at end of file
diff --git a/actionpack/test/fixtures/test/utf8.html.erb b/actionpack/test/fixtures/test/utf8.html.erb
index 0b4d19aa0e..58cd03b439 100644
--- a/actionpack/test/fixtures/test/utf8.html.erb
+++ b/actionpack/test/fixtures/test/utf8.html.erb
@@ -1,2 +1,5 @@
+<%# encoding: utf-8 -%>
Русский текст
-日本語のテキスト \ No newline at end of file
+<%= "日".encoding %>
+<%= @output_buffer.encoding %>
+<%= __ENCODING__ %>
diff --git a/actionpack/test/controller/html-scanner/cdata_node_test.rb b/actionpack/test/html-scanner/cdata_node_test.rb
index 1822cc565a..1822cc565a 100644
--- a/actionpack/test/controller/html-scanner/cdata_node_test.rb
+++ b/actionpack/test/html-scanner/cdata_node_test.rb
diff --git a/actionpack/test/controller/html-scanner/document_test.rb b/actionpack/test/html-scanner/document_test.rb
index c68f04fa75..c68f04fa75 100644
--- a/actionpack/test/controller/html-scanner/document_test.rb
+++ b/actionpack/test/html-scanner/document_test.rb
diff --git a/actionpack/test/controller/html-scanner/node_test.rb b/actionpack/test/html-scanner/node_test.rb
index b0df36877e..b0df36877e 100644
--- a/actionpack/test/controller/html-scanner/node_test.rb
+++ b/actionpack/test/html-scanner/node_test.rb
diff --git a/actionpack/test/controller/html-scanner/sanitizer_test.rb b/actionpack/test/html-scanner/sanitizer_test.rb
index e85a5c7abf..e85a5c7abf 100644
--- a/actionpack/test/controller/html-scanner/sanitizer_test.rb
+++ b/actionpack/test/html-scanner/sanitizer_test.rb
diff --git a/actionpack/test/controller/html-scanner/tag_node_test.rb b/actionpack/test/html-scanner/tag_node_test.rb
index d1d4667378..d1d4667378 100644
--- a/actionpack/test/controller/html-scanner/tag_node_test.rb
+++ b/actionpack/test/html-scanner/tag_node_test.rb
diff --git a/actionpack/test/controller/html-scanner/text_node_test.rb b/actionpack/test/html-scanner/text_node_test.rb
index 1ab3f4454e..1ab3f4454e 100644
--- a/actionpack/test/controller/html-scanner/text_node_test.rb
+++ b/actionpack/test/html-scanner/text_node_test.rb
diff --git a/actionpack/test/controller/html-scanner/tokenizer_test.rb b/actionpack/test/html-scanner/tokenizer_test.rb
index a001bcbbad..a001bcbbad 100644
--- a/actionpack/test/controller/html-scanner/tokenizer_test.rb
+++ b/actionpack/test/html-scanner/tokenizer_test.rb
diff --git a/actionpack/test/active_record_unit.rb b/actionpack/test/lib/active_record_unit.rb
index 9e0c66055d..1ba308e9d7 100644
--- a/actionpack/test/active_record_unit.rb
+++ b/actionpack/test/lib/active_record_unit.rb
@@ -16,7 +16,7 @@ if defined?(ActiveRecord) && defined?(Fixtures)
else
$stderr.print 'Attempting to load Active Record... '
begin
- PATH_TO_AR = "#{File.dirname(__FILE__)}/../../activerecord/lib"
+ PATH_TO_AR = "#{File.dirname(__FILE__)}/../../../activerecord/lib"
raise LoadError, "#{PATH_TO_AR} doesn't exist" unless File.directory?(PATH_TO_AR)
$LOAD_PATH.unshift PATH_TO_AR
require 'active_record'
@@ -72,13 +72,13 @@ class ActiveRecordTestConnector
# Load actionpack sqlite tables
def load_schema
- File.read(File.dirname(__FILE__) + "/fixtures/db_definitions/sqlite.sql").split(';').each do |sql|
+ File.read(File.dirname(__FILE__) + "/../fixtures/db_definitions/sqlite.sql").split(';').each do |sql|
ActiveRecord::Base.connection.execute(sql) unless sql.blank?
end
end
def require_fixture_models
- Dir.glob(File.dirname(__FILE__) + "/fixtures/*.rb").each {|f| require f}
+ Dir.glob(File.dirname(__FILE__) + "/../fixtures/*.rb").each {|f| require f}
end
end
end
diff --git a/actionpack/test/controller/fake_controllers.rb b/actionpack/test/lib/controller/fake_controllers.rb
index 75c114c103..75c114c103 100644
--- a/actionpack/test/controller/fake_controllers.rb
+++ b/actionpack/test/lib/controller/fake_controllers.rb
diff --git a/actionpack/test/controller/fake_models.rb b/actionpack/test/lib/controller/fake_models.rb
index 0b30c79b10..0b30c79b10 100644
--- a/actionpack/test/controller/fake_models.rb
+++ b/actionpack/test/lib/controller/fake_models.rb
diff --git a/actionpack/test/lib/fixture_template.rb b/actionpack/test/lib/fixture_template.rb
index 26f6ec2d0c..59fb6819ed 100644
--- a/actionpack/test/lib/fixture_template.rb
+++ b/actionpack/test/lib/fixture_template.rb
@@ -1,35 +1,104 @@
module ActionView #:nodoc:
- class FixtureTemplate < Template
- class FixturePath < Template::Path
- def initialize(hash = {})
- @hash = {}
-
- hash.each do |k, v|
- @hash[k.sub(/\.\w+$/, '')] = FixtureTemplate.new(v, k.split("/").last, self)
+class Template
+ class FixturePath < Path
+ def initialize(hash = {}, options = {})
+ super(options)
+ @hash = hash
+ end
+
+ def find_templates(name, details, prefix, partial)
+ if regexp = details_to_regexp(name, details, prefix, partial)
+ cached(regexp) do
+ templates = []
+ @hash.select { |k,v| k =~ regexp }.each do |path, source|
+ templates << Template.new(source, path, *path_to_details(path))
+ end
+ templates
end
-
- super("fixtures://root")
- end
-
- def find_template(path)
- @hash[path]
end
end
- def initialize(body, *args)
- @body = body
- super(*args)
+ private
+
+ def formats_regexp
+ @formats_regexp ||= begin
+ formats = Mime::SET.map { |m| m.symbol }
+ '(?:' + formats.map { |l| "\\.#{Regexp.escape(l.to_s)}" }.join('|') + ')?'
+ end
end
- def source
- @body
+ def handler_regexp
+ e = TemplateHandlers.extensions.map{|h| "\\.#{Regexp.escape(h.to_s)}"}.join("|")
+ "(?:#{e})?"
end
- private
-
- def find_full_path(path, load_paths)
- return '/', path
+ def details_to_regexp(name, details, prefix, partial)
+ path = ""
+ path << "#{prefix}/" unless prefix.empty?
+ path << (partial ? "_#{name}" : name)
+
+ extensions = ""
+ [:locales, :formats].each do |k|
+ extensions << if exts = details[k]
+ '(?:' + exts.map {|e| "\\.#{Regexp.escape(e.to_s)}"}.join('|') + ')?'
+ else
+ k == :formats ? formats_regexp : ''
+ end
+ end
+
+ %r'^#{Regexp.escape(path)}#{extensions}#{handler_regexp}$'
+ end
+
+ # TODO: fix me
+ # :api: plugin
+ def path_to_details(path)
+ # [:erb, :format => :html, :locale => :en, :partial => true/false]
+ if m = path.match(%r'(_)?[\w-]+(\.[\w-]+)*\.(\w+)$')
+ partial = m[1] == '_'
+ details = (m[2]||"").split('.').reject { |e| e.empty? }
+ handler = Template.handler_class_for_extension(m[3])
+
+ format = Mime[details.last] && details.pop.to_sym
+ locale = details.last && details.pop.to_sym
+
+ return handler, :format => format, :locale => locale, :partial => partial
+ end
end
-
end
+
+
+ # class FixtureTemplate < Template
+ # class FixturePath < Template::Path
+ # def initialize(hash = {})
+ # @hash = {}
+ #
+ # hash.each do |k, v|
+ # @hash[k.sub(/\.\w+$/, '')] = FixtureTemplate.new(v, k.split("/").last, self)
+ # end
+ #
+ # super("fixtures://root")
+ # end
+ #
+ # def find_template(path)
+ # @hash[path]
+ # end
+ # end
+ #
+ # def initialize(body, *args)
+ # @body = body
+ # super(*args)
+ # end
+ #
+ # def source
+ # @body
+ # end
+ #
+ # private
+ #
+ # def find_full_path(path, load_paths)
+ # return '/', path
+ # end
+ #
+ # end
+end
end \ No newline at end of file
diff --git a/actionpack/test/testing_sandbox.rb b/actionpack/test/lib/testing_sandbox.rb
index c36585104f..c36585104f 100644
--- a/actionpack/test/testing_sandbox.rb
+++ b/actionpack/test/lib/testing_sandbox.rb
diff --git a/actionpack/test/new_base/abstract_unit.rb b/actionpack/test/new_base/abstract_unit.rb
new file mode 100644
index 0000000000..e6690d41d9
--- /dev/null
+++ b/actionpack/test/new_base/abstract_unit.rb
@@ -0,0 +1,166 @@
+$:.unshift(File.dirname(__FILE__) + '/../../lib')
+$:.unshift(File.dirname(__FILE__) + '/../../../activesupport/lib')
+$:.unshift(File.dirname(__FILE__) + '/../lib')
+
+$:.unshift(File.dirname(__FILE__) + '/../fixtures/helpers')
+$:.unshift(File.dirname(__FILE__) + '/../fixtures/alternate_helpers')
+
+ENV['new_base'] = "true"
+$stderr.puts "Running old tests on new_base"
+
+require 'test/unit'
+require 'active_support'
+
+# TODO : Revisit requiring all the core extensions here
+require 'active_support/core_ext'
+
+require 'active_support/test_case'
+require 'action_controller/abstract'
+require 'action_controller/new_base'
+require 'fixture_template'
+require 'action_controller/testing/process2'
+require 'action_view/test_case'
+require 'action_controller/testing/integration'
+require 'active_support/dependencies'
+
+$tags[:new_base] = true
+
+begin
+ require 'ruby-debug'
+ Debugger.settings[:autoeval] = true
+ Debugger.start
+rescue LoadError
+ # Debugging disabled. `gem install ruby-debug` to enable.
+end
+
+ActiveSupport::Dependencies.hook!
+
+# Show backtraces for deprecated behavior for quicker cleanup.
+ActiveSupport::Deprecation.debug = true
+
+# Register danish language for testing
+I18n.backend.store_translations 'da', {}
+I18n.backend.store_translations 'pt-BR', {}
+ORIGINAL_LOCALES = I18n.available_locales.map {|locale| locale.to_s }.sort
+
+FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), '../fixtures')
+
+module ActionController
+ Base.session = {
+ :key => '_testing_session',
+ :secret => '8273f16463985e2b3747dc25e30f2528'
+}
+
+ class ActionControllerError < StandardError #:nodoc:
+ end
+
+ class SessionRestoreError < ActionControllerError #:nodoc:
+ end
+
+ class RenderError < ActionControllerError #:nodoc:
+ end
+
+ class RoutingError < ActionControllerError #:nodoc:
+ attr_reader :failures
+ def initialize(message, failures=[])
+ super(message)
+ @failures = failures
+ end
+ end
+
+ class MethodNotAllowed < ActionControllerError #:nodoc:
+ attr_reader :allowed_methods
+
+ def initialize(*allowed_methods)
+ super("Only #{allowed_methods.to_sentence(:locale => :en)} requests are allowed.")
+ @allowed_methods = allowed_methods
+ end
+
+ def allowed_methods_header
+ allowed_methods.map { |method_symbol| method_symbol.to_s.upcase } * ', '
+ end
+
+ def handle_response!(response)
+ response.headers['Allow'] ||= allowed_methods_header
+ end
+ end
+
+ class NotImplemented < MethodNotAllowed #:nodoc:
+ end
+
+ class UnknownController < ActionControllerError #:nodoc:
+ end
+
+ class MissingFile < ActionControllerError #:nodoc:
+ end
+
+ class RenderError < ActionControllerError #:nodoc:
+ end
+
+ class SessionOverflowError < ActionControllerError #:nodoc:
+ DEFAULT_MESSAGE = 'Your session data is larger than the data column in which it is to be stored. You must increase the size of your data column if you intend to store large data.'
+
+ def initialize(message = nil)
+ super(message || DEFAULT_MESSAGE)
+ end
+ end
+
+ class UnknownHttpMethod < ActionControllerError #:nodoc:
+ end
+
+ class Base
+ include ActionController::Testing
+ end
+
+ Base.view_paths = FIXTURE_LOAD_PATH
+
+ class TestCase
+ include TestProcess
+ setup do
+ ActionController::Routing::Routes.draw do |map|
+ map.connect ':controller/:action/:id'
+ end
+ end
+
+ def assert_template(options = {}, message = nil)
+ validate_request!
+
+ hax = @controller._action_view.instance_variable_get(:@_rendered)
+
+ case options
+ when NilClass, String
+ rendered = (hax[:template] || []).map { |t| t.identifier }
+ msg = build_message(message,
+ "expecting <?> but rendering with <?>",
+ options, rendered.join(', '))
+ assert_block(msg) do
+ if options.nil?
+ hax[:template].blank?
+ else
+ rendered.any? { |t| t.match(options) }
+ end
+ end
+ when Hash
+ if expected_partial = options[:partial]
+ partials = hax[:partials]
+ if expected_count = options[:count]
+ found = partials.detect { |p, _| p.identifier.match(expected_partial) }
+ actual_count = found.nil? ? 0 : found.second
+ msg = build_message(message,
+ "expecting ? to be rendered ? time(s) but rendered ? time(s)",
+ expected_partial, expected_count, actual_count)
+ assert(actual_count == expected_count.to_i, msg)
+ else
+ msg = build_message(message,
+ "expecting partial <?> but action rendered <?>",
+ options[:partial], partials.keys)
+ assert(partials.keys.any? { |p| p.identifier.match(expected_partial) }, msg)
+ end
+ else
+ assert hax[:partials].empty?,
+ "Expected no partials to be rendered"
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/test/new_base/base_test.rb b/actionpack/test/new_base/base_test.rb
index 4f46cb6492..d9d552f9e5 100644
--- a/actionpack/test/new_base/base_test.rb
+++ b/actionpack/test/new_base/base_test.rb
@@ -1,8 +1,8 @@
require File.join(File.expand_path(File.dirname(__FILE__)), "test_helper")
# Tests the controller dispatching happy path
-module HappyPath
- class SimpleDispatchController < ActionController::Base2
+module Dispatching
+ class SimpleController < ActionController::Base
def index
render :text => "success"
end
@@ -10,81 +10,62 @@ module HappyPath
def modify_response_body
self.response_body = "success"
end
-
+
def modify_response_body_twice
ret = (self.response_body = "success")
self.response_body = "#{ret}!"
end
-
+
def modify_response_headers
-
end
end
-
- class TestSimpleDispatch < SimpleRouteCase
-
- get "/happy_path/simple_dispatch/index"
-
- test "sets the body" do
+
+ class EmptyController < ActionController::Base ; end
+
+ module Submodule
+ class ContainedEmptyController < ActionController::Base ; end
+ end
+
+ class BaseTest < SimpleRouteCase
+ # :api: plugin
+ test "simple dispatching" do
+ get "/dispatching/simple/index"
+
assert_body "success"
- end
-
- test "sets the status code" do
assert_status 200
+ assert_content_type "text/html; charset=utf-8"
+ assert_header "Content-Length", "7"
end
-
- test "sets the content type" do
- assert_content_type Mime::HTML
- end
-
- test "sets the content length" do
- assert_header "Content-Length", 7
- end
-
- end
-
- # :api: plugin
- class TestDirectResponseMod < SimpleRouteCase
- get "/happy_path/simple_dispatch/modify_response_body"
-
- test "sets the body" do
+
+ # :api: plugin
+ test "directly modifying response body" do
+ get "/dispatching/simple/modify_response_body"
+
assert_body "success"
+ assert_header "Content-Length", "7" # setting the body manually sets the content length
end
-
- test "setting the body manually sets the content length" do
- assert_header "Content-Length", 7
- end
- end
-
- # :api: plugin
- class TestDirectResponseModTwice < SimpleRouteCase
- get "/happy_path/simple_dispatch/modify_response_body_twice"
-
- test "self.response_body= returns the body being set" do
+
+ # :api: plugin
+ test "directly modifying response body twice" do
+ get "/dispatching/simple/modify_response_body_twice"
+
assert_body "success!"
+ assert_header "Content-Length", "8"
end
-
- test "updating the response body updates the content length" do
- assert_header "Content-Length", 8
- end
- end
-end
+ test "controller path" do
+ assert_equal 'dispatching/empty', EmptyController.controller_path
+ assert_equal EmptyController.controller_path, EmptyController.new.controller_path
+ end
-class EmptyController < ActionController::Base2 ; end
-module Submodule
- class ContainedEmptyController < ActionController::Base2 ; end
-end
+ test "namespaced controller path" do
+ assert_equal 'dispatching/submodule/contained_empty', Submodule::ContainedEmptyController.controller_path
+ assert_equal Submodule::ContainedEmptyController.controller_path, Submodule::ContainedEmptyController.new.controller_path
+ end
-class ControllerClassTests < Test::Unit::TestCase
- def test_controller_path
- assert_equal 'empty', EmptyController.controller_path
- assert_equal EmptyController.controller_path, EmptyController.new.controller_path
- assert_equal 'submodule/contained_empty', Submodule::ContainedEmptyController.controller_path
- assert_equal Submodule::ContainedEmptyController.controller_path, Submodule::ContainedEmptyController.new.controller_path
+ test "controller name" do
+ assert_equal 'empty', EmptyController.controller_name
+ assert_equal 'contained_empty', Submodule::ContainedEmptyController.controller_name
+ end
end
- def test_controller_name
- assert_equal 'empty', EmptyController.controller_name
- assert_equal 'contained_empty', Submodule::ContainedEmptyController.controller_name
- end
end \ No newline at end of file
diff --git a/actionpack/test/new_base/content_type_test.rb b/actionpack/test/new_base/content_type_test.rb
new file mode 100644
index 0000000000..82b817a5a3
--- /dev/null
+++ b/actionpack/test/new_base/content_type_test.rb
@@ -0,0 +1,111 @@
+require File.join(File.expand_path(File.dirname(__FILE__)), "test_helper")
+
+module ContentType
+ class BaseController < ActionController::Base
+ def index
+ render :text => "Hello world!"
+ end
+
+ def set_on_response_obj
+ response.content_type = Mime::RSS
+ render :text => "Hello world!"
+ end
+
+ def set_on_render
+ render :text => "Hello world!", :content_type => Mime::RSS
+ end
+ end
+
+ class ImpliedController < ActionController::Base
+ # Template's mime type is used if no content_type is specified
+
+ self.view_paths = [ActionView::Template::FixturePath.new(
+ "content_type/implied/i_am_html_erb.html.erb" => "Hello world!",
+ "content_type/implied/i_am_xml_erb.xml.erb" => "<xml>Hello world!</xml>",
+ "content_type/implied/i_am_html_builder.html.builder" => "xml.p 'Hello'",
+ "content_type/implied/i_am_xml_builder.xml.builder" => "xml.awesome 'Hello'"
+ )]
+
+ def i_am_html_erb() end
+ def i_am_xml_erb() end
+ def i_am_html_builder() end
+ def i_am_xml_builder() end
+ end
+
+ class CharsetController < ActionController::Base
+ def set_on_response_obj
+ response.charset = "utf-16"
+ render :text => "Hello world!"
+ end
+
+ def set_as_nil_on_response_obj
+ response.charset = nil
+ render :text => "Hello world!"
+ end
+ end
+
+ class ExplicitContentTypeTest < SimpleRouteCase
+ test "default response is HTML and UTF8" do
+ get "/content_type/base"
+
+ assert_body "Hello world!"
+ assert_header "Content-Type", "text/html; charset=utf-8"
+ end
+
+ test "setting the content type of the response directly on the response object" do
+ get "/content_type/base/set_on_response_obj"
+
+ assert_body "Hello world!"
+ assert_header "Content-Type", "application/rss+xml; charset=utf-8"
+ end
+
+ test "setting the content type of the response as an option to render" do
+ get "/content_type/base/set_on_render"
+
+ assert_body "Hello world!"
+ assert_header "Content-Type", "application/rss+xml; charset=utf-8"
+ end
+ end
+
+ class ImpliedContentTypeTest < SimpleRouteCase
+ test "sets Content-Type as text/html when rendering *.html.erb" do
+ get "/content_type/implied/i_am_html_erb"
+
+ assert_header "Content-Type", "text/html; charset=utf-8"
+ end
+
+ test "sets Content-Type as application/xml when rendering *.xml.erb" do
+ get "/content_type/implied/i_am_xml_erb"
+
+ assert_header "Content-Type", "application/xml; charset=utf-8"
+ end
+
+ test "sets Content-Type as text/html when rendering *.html.builder" do
+ get "/content_type/implied/i_am_html_builder"
+
+ assert_header "Content-Type", "text/html; charset=utf-8"
+ end
+
+ test "sets Content-Type as application/xml when rendering *.xml.builder" do
+ get "/content_type/implied/i_am_xml_builder"
+
+ assert_header "Content-Type", "application/xml; charset=utf-8"
+ end
+ end
+
+ class ExplicitCharsetTest < SimpleRouteCase
+ test "setting the charset of the response directly on the response object" do
+ get "/content_type/charset/set_on_response_obj"
+
+ assert_body "Hello world!"
+ assert_header "Content-Type", "text/html; charset=utf-16"
+ end
+
+ test "setting the charset of the response as nil directly on the response object" do
+ get "/content_type/charset/set_as_nil_on_response_obj"
+
+ assert_body "Hello world!"
+ assert_header "Content-Type", "text/html; charset=utf-8"
+ end
+ end
+end
diff --git a/actionpack/test/new_base/etag_test.rb b/actionpack/test/new_base/etag_test.rb
new file mode 100644
index 0000000000..a40d3c936a
--- /dev/null
+++ b/actionpack/test/new_base/etag_test.rb
@@ -0,0 +1,46 @@
+require File.join(File.expand_path(File.dirname(__FILE__)), "test_helper")
+
+module Etags
+ class BasicController < ActionController::Base
+ self.view_paths = [ActionView::Template::FixturePath.new(
+ "etags/basic/base.html.erb" => "Hello from without_layout.html.erb",
+ "layouts/etags.html.erb" => "teh <%= yield %> tagz"
+ )]
+
+ def without_layout
+ render :action => "base"
+ end
+
+ def with_layout
+ render :action => "base", :layout => "etags"
+ end
+ end
+
+ class EtagTest < SimpleRouteCase
+ describe "Rendering without any special etag options returns an etag that is an MD5 hash of its text"
+
+ test "an action without a layout" do
+ get "/etags/basic/without_layout"
+
+ body = "Hello from without_layout.html.erb"
+ assert_body body
+ assert_header "Etag", etag_for(body)
+ assert_status 200
+ end
+
+ test "an action with a layout" do
+ get "/etags/basic/with_layout"
+
+ body = "teh Hello from without_layout.html.erb tagz"
+ assert_body body
+ assert_header "Etag", etag_for(body)
+ assert_status 200
+ end
+
+ private
+
+ def etag_for(text)
+ %("#{Digest::MD5.hexdigest(text)}")
+ end
+ end
+end \ No newline at end of file
diff --git a/actionpack/test/new_base/redirect_test.rb b/actionpack/test/new_base/redirect_test.rb
new file mode 100644
index 0000000000..e591ebd05f
--- /dev/null
+++ b/actionpack/test/new_base/redirect_test.rb
@@ -0,0 +1 @@
+require File.join(File.expand_path(File.dirname(__FILE__)), "test_helper") \ No newline at end of file
diff --git a/actionpack/test/new_base/render_action_test.rb b/actionpack/test/new_base/render_action_test.rb
index 2bfb374a31..4402eadf42 100644
--- a/actionpack/test/new_base/render_action_test.rb
+++ b/actionpack/test/new_base/render_action_test.rb
@@ -1,26 +1,24 @@
require File.join(File.expand_path(File.dirname(__FILE__)), "test_helper")
module RenderAction
-
# This has no layout and it works
- class BasicController < ActionController::Base2
-
- self.view_paths = [ActionView::FixtureTemplate::FixturePath.new(
+ class BasicController < ActionController::Base
+ self.view_paths = [ActionView::Template::FixturePath.new(
"render_action/basic/hello_world.html.erb" => "Hello world!"
)]
-
+
def hello_world
render :action => "hello_world"
end
-
+
def hello_world_as_string
render "hello_world"
end
-
+
def hello_world_as_string_with_options
render "hello_world", :status => 404
end
-
+
def hello_world_as_symbol
render :hello_world
end
@@ -28,298 +26,295 @@ module RenderAction
def hello_world_with_symbol
render :action => :hello_world
end
-
+
def hello_world_with_layout
render :action => "hello_world", :layout => true
end
-
+
def hello_world_with_layout_false
render :action => "hello_world", :layout => false
end
-
+
def hello_world_with_layout_nil
render :action => "hello_world", :layout => nil
end
-
+
def hello_world_with_custom_layout
render :action => "hello_world", :layout => "greetings"
end
-
- end
-
- class TestBasic < SimpleRouteCase
- describe "Rendering an action using :action => <String>"
-
- get "/render_action/basic/hello_world"
- assert_body "Hello world!"
- assert_status 200
- end
-
- class TestWithString < SimpleRouteCase
- describe "Render an action using 'hello_world'"
-
- get "/render_action/basic/hello_world_as_string"
- assert_body "Hello world!"
- assert_status 200
- end
-
- class TestWithStringAndOptions < SimpleRouteCase
- describe "Render an action using 'hello_world'"
-
- get "/render_action/basic/hello_world_as_string_with_options"
- assert_body "Hello world!"
- assert_status 404
- end
-
- class TestAsSymbol < SimpleRouteCase
- describe "Render an action using :hello_world"
-
- get "/render_action/basic/hello_world_as_symbol"
- assert_body "Hello world!"
- assert_status 200
+
end
-
- class TestWithSymbol < SimpleRouteCase
- describe "Render an action using :action => :hello_world"
-
- get "/render_action/basic/hello_world_with_symbol"
- assert_body "Hello world!"
- assert_status 200
+
+ class RenderActionTest < SimpleRouteCase
+ test "rendering an action using :action => <String>" do
+ get "/render_action/basic/hello_world"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
+
+ test "rendering an action using '<action>'" do
+ get "/render_action/basic/hello_world_as_string"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
+
+ test "rendering an action using '<action>' and options" do
+ get "/render_action/basic/hello_world_as_string_with_options"
+
+ assert_body "Hello world!"
+ assert_status 404
+ end
+
+ test "rendering an action using :action" do
+ get "/render_action/basic/hello_world_as_symbol"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
+
+ test "rendering an action using :action => :hello_world" do
+ get "/render_action/basic/hello_world_with_symbol"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
end
-
- class TestLayoutTrue < SimpleRouteCase
- describe "rendering a normal template with full path with layout => true"
-
- test "raises an exception when requesting a layout and none exist" do
- assert_raise(ArgumentError, /no default layout for RenderAction::BasicController in/) do
- get "/render_action/basic/hello_world_with_layout"
+
+ class RenderLayoutTest < SimpleRouteCase
+ describe "Both <controller_path>.html.erb and application.html.erb are missing"
+
+ test "rendering with layout => true" do
+ assert_raise(ArgumentError, /no default layout for RenderAction::BasicController in/) do
+ get "/render_action/basic/hello_world_with_layout", {}, "action_dispatch.show_exceptions" => false
end
end
- end
-
- class TestLayoutFalse < SimpleRouteCase
- describe "rendering a normal template with full path with layout => false"
-
- get "/render_action/basic/hello_world_with_layout_false"
- assert_body "Hello world!"
- assert_status 200
- end
-
- class TestLayoutNil < SimpleRouteCase
- describe "rendering a normal template with full path with layout => :nil"
-
- get "/render_action/basic/hello_world_with_layout_nil"
- assert_body "Hello world!"
- assert_status 200
- end
-
- class TestCustomLayout < SimpleRouteCase
- describe "rendering a normal template with full path with layout => 'greetings'"
-
- test "raises an exception when requesting a layout that does not exist" do
- assert_raise(ActionView::MissingTemplate) { get "/render_action/basic/hello_world_with_custom_layout" }
+
+ test "rendering with layout => false" do
+ get "/render_action/basic/hello_world_with_layout_false"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
+
+ test "rendering with layout => :nil" do
+ get "/render_action/basic/hello_world_with_layout_nil"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
+
+ test "rendering with layout => 'greetings'" do
+ assert_raise(ActionView::MissingTemplate) do
+ get "/render_action/basic/hello_world_with_custom_layout", {}, "action_dispatch.show_exceptions" => false
+ end
end
end
-
end
module RenderActionWithApplicationLayout
-
# # ==== Render actions with layouts ====
-
class BasicController < ::ApplicationController
# Set the view path to an application view structure with layouts
- self.view_paths = self.view_paths = [ActionView::FixtureTemplate::FixturePath.new(
+ self.view_paths = self.view_paths = [ActionView::Template::FixturePath.new(
"render_action_with_application_layout/basic/hello_world.html.erb" => "Hello World!",
+ "render_action_with_application_layout/basic/hello.html.builder" => "xml.p 'Omg'",
"layouts/application.html.erb" => "OHAI <%= yield %> KTHXBAI",
- "layouts/greetings.html.erb" => "Greetings <%= yield %> Bai"
+ "layouts/greetings.html.erb" => "Greetings <%= yield %> Bai",
+ "layouts/builder.html.builder" => "xml.html do\n xml << yield\nend"
)]
-
+
def hello_world
render :action => "hello_world"
end
-
+
def hello_world_with_layout
render :action => "hello_world", :layout => true
end
-
+
def hello_world_with_layout_false
render :action => "hello_world", :layout => false
end
-
+
def hello_world_with_layout_nil
render :action => "hello_world", :layout => nil
end
-
+
def hello_world_with_custom_layout
render :action => "hello_world", :layout => "greetings"
end
+
+ def with_builder_and_layout
+ render :action => "hello", :layout => "builder"
+ end
end
-
- class TestDefaultLayout < SimpleRouteCase
- describe %(
- Render hello_world and implicitly use application.html.erb as a layout if
- no layout is specified and no controller layout is present
- )
-
- get "/render_action_with_application_layout/basic/hello_world"
- assert_body "OHAI Hello World! KTHXBAI"
- assert_status 200
- end
-
- class TestLayoutTrue < SimpleRouteCase
- describe "rendering a normal template with full path with layout => true"
-
- get "/render_action_with_application_layout/basic/hello_world_with_layout"
- assert_body "OHAI Hello World! KTHXBAI"
- assert_status 200
- end
-
- class TestLayoutFalse < SimpleRouteCase
- describe "rendering a normal template with full path with layout => false"
-
- get "/render_action_with_application_layout/basic/hello_world_with_layout_false"
- assert_body "Hello World!"
- assert_status 200
- end
-
- class TestLayoutNil < SimpleRouteCase
- describe "rendering a normal template with full path with layout => :nil"
-
- get "/render_action_with_application_layout/basic/hello_world_with_layout_nil"
- assert_body "Hello World!"
- assert_status 200
+
+ class LayoutTest < SimpleRouteCase
+ describe "Only application.html.erb is present and <controller_path>.html.erb is missing"
+
+ test "rendering implicit application.html.erb as layout" do
+ get "/render_action_with_application_layout/basic/hello_world"
+
+ assert_body "OHAI Hello World! KTHXBAI"
+ assert_status 200
+ end
+
+ test "rendering with layout => true" do
+ get "/render_action_with_application_layout/basic/hello_world_with_layout"
+
+ assert_body "OHAI Hello World! KTHXBAI"
+ assert_status 200
+ end
+
+ test "rendering with layout => false" do
+ get "/render_action_with_application_layout/basic/hello_world_with_layout_false"
+
+ assert_body "Hello World!"
+ assert_status 200
+ end
+
+ test "rendering with layout => :nil" do
+ get "/render_action_with_application_layout/basic/hello_world_with_layout_nil"
+
+ assert_body "Hello World!"
+ assert_status 200
+ end
+
+ test "rendering with layout => 'greetings'" do
+ get "/render_action_with_application_layout/basic/hello_world_with_custom_layout"
+
+ assert_body "Greetings Hello World! Bai"
+ assert_status 200
+ end
end
-
- class TestCustomLayout < SimpleRouteCase
- describe "rendering a normal template with full path with layout => 'greetings'"
-
- get "/render_action_with_application_layout/basic/hello_world_with_custom_layout"
- assert_body "Greetings Hello World! Bai"
- assert_status 200
+
+ class TestLayout < SimpleRouteCase
+ testing BasicController
+
+ test "builder works with layouts" do
+ get :with_builder_and_layout
+ assert_response "<html>\n<p>Omg</p>\n</html>\n"
+ end
end
-
+
end
module RenderActionWithControllerLayout
-
- class BasicController < ActionController::Base2
- self.view_paths = self.view_paths = [ActionView::FixtureTemplate::FixturePath.new(
+ class BasicController < ActionController::Base
+ self.view_paths = self.view_paths = [ActionView::Template::FixturePath.new(
"render_action_with_controller_layout/basic/hello_world.html.erb" => "Hello World!",
"layouts/render_action_with_controller_layout/basic.html.erb" => "With Controller Layout! <%= yield %> KTHXBAI"
)]
-
+
def hello_world
render :action => "hello_world"
end
-
+
def hello_world_with_layout
render :action => "hello_world", :layout => true
end
-
+
def hello_world_with_layout_false
render :action => "hello_world", :layout => false
end
-
+
def hello_world_with_layout_nil
render :action => "hello_world", :layout => nil
end
-
+
def hello_world_with_custom_layout
render :action => "hello_world", :layout => "greetings"
end
end
-
- class TestControllerLayout < SimpleRouteCase
- describe "Render hello_world and implicitly use <controller_path>.html.erb as a layout."
- get "/render_action_with_controller_layout/basic/hello_world"
- assert_body "With Controller Layout! Hello World! KTHXBAI"
- assert_status 200
- end
-
- class TestLayoutTrue < SimpleRouteCase
- describe "rendering a normal template with full path with layout => true"
-
- get "/render_action_with_controller_layout/basic/hello_world_with_layout"
- assert_body "With Controller Layout! Hello World! KTHXBAI"
- assert_status 200
- end
-
- class TestLayoutFalse < SimpleRouteCase
- describe "rendering a normal template with full path with layout => false"
-
- get "/render_action_with_controller_layout/basic/hello_world_with_layout_false"
- assert_body "Hello World!"
- assert_status 200
- end
-
- class TestLayoutNil < SimpleRouteCase
- describe "rendering a normal template with full path with layout => :nil"
-
- get "/render_action_with_controller_layout/basic/hello_world_with_layout_nil"
- assert_body "Hello World!"
- assert_status 200
+ class ControllerLayoutTest < SimpleRouteCase
+ describe "Only <controller_path>.html.erb is present and application.html.erb is missing"
+
+ test "render hello_world and implicitly use <controller_path>.html.erb as a layout." do
+ get "/render_action_with_controller_layout/basic/hello_world"
+
+ assert_body "With Controller Layout! Hello World! KTHXBAI"
+ assert_status 200
+ end
+
+ test "rendering with layout => true" do
+ get "/render_action_with_controller_layout/basic/hello_world_with_layout"
+
+ assert_body "With Controller Layout! Hello World! KTHXBAI"
+ assert_status 200
+ end
+
+ test "rendering with layout => false" do
+ get "/render_action_with_controller_layout/basic/hello_world_with_layout_false"
+
+ assert_body "Hello World!"
+ assert_status 200
+ end
+
+ test "rendering with layout => :nil" do
+ get "/render_action_with_controller_layout/basic/hello_world_with_layout_nil"
+
+ assert_body "Hello World!"
+ assert_status 200
+ end
end
-
end
module RenderActionWithBothLayouts
-
- class BasicController < ActionController::Base2
- self.view_paths = [ActionView::FixtureTemplate::FixturePath.new({
+ class BasicController < ActionController::Base
+ self.view_paths = [ActionView::Template::FixturePath.new({
"render_action_with_both_layouts/basic/hello_world.html.erb" => "Hello World!",
"layouts/application.html.erb" => "OHAI <%= yield %> KTHXBAI",
"layouts/render_action_with_both_layouts/basic.html.erb" => "With Controller Layout! <%= yield %> KTHXBAI"
})]
-
+
def hello_world
render :action => "hello_world"
end
-
+
def hello_world_with_layout
render :action => "hello_world", :layout => true
end
-
+
def hello_world_with_layout_false
render :action => "hello_world", :layout => false
end
-
+
def hello_world_with_layout_nil
render :action => "hello_world", :layout => nil
end
end
-
- class TestControllerLayoutFirst < SimpleRouteCase
- describe "Render hello_world and implicitly use <controller_path>.html.erb over application.html.erb as a layout"
- get "/render_action_with_both_layouts/basic/hello_world"
- assert_body "With Controller Layout! Hello World! KTHXBAI"
- assert_status 200
- end
-
- class TestLayoutTrue < SimpleRouteCase
- describe "rendering a normal template with full path with layout => true"
-
- get "/render_action_with_both_layouts/basic/hello_world_with_layout"
- assert_body "With Controller Layout! Hello World! KTHXBAI"
- assert_status 200
- end
-
- class TestLayoutFalse < SimpleRouteCase
- describe "rendering a normal template with full path with layout => false"
-
- get "/render_action_with_both_layouts/basic/hello_world_with_layout_false"
- assert_body "Hello World!"
- assert_status 200
- end
-
- class TestLayoutNil < SimpleRouteCase
- describe "rendering a normal template with full path with layout => :nil"
-
- get "/render_action_with_both_layouts/basic/hello_world_with_layout_nil"
- assert_body "Hello World!"
- assert_status 200
+ class ControllerLayoutTest < SimpleRouteCase
+ describe "Both <controller_path>.html.erb and application.html.erb are present"
+
+ test "rendering implicitly use <controller_path>.html.erb over application.html.erb as a layout" do
+ get "/render_action_with_both_layouts/basic/hello_world"
+
+ assert_body "With Controller Layout! Hello World! KTHXBAI"
+ assert_status 200
+ end
+
+ test "rendering with layout => true" do
+ get "/render_action_with_both_layouts/basic/hello_world_with_layout"
+
+ assert_body "With Controller Layout! Hello World! KTHXBAI"
+ assert_status 200
+ end
+
+ test "rendering with layout => false" do
+ get "/render_action_with_both_layouts/basic/hello_world_with_layout_false"
+
+ assert_body "Hello World!"
+ assert_status 200
+ end
+
+ test "rendering with layout => :nil" do
+ get "/render_action_with_both_layouts/basic/hello_world_with_layout_nil"
+
+ assert_body "Hello World!"
+ assert_status 200
+ end
end
-
end \ No newline at end of file
diff --git a/actionpack/test/new_base/render_file_test.rb b/actionpack/test/new_base/render_file_test.rb
new file mode 100644
index 0000000000..769949be0c
--- /dev/null
+++ b/actionpack/test/new_base/render_file_test.rb
@@ -0,0 +1,110 @@
+require File.join(File.expand_path(File.dirname(__FILE__)), "test_helper")
+
+module RenderFile
+
+ class BasicController < ActionController::Base
+ self.view_paths = "."
+
+ def index
+ render :file => File.join(File.dirname(__FILE__), *%w[.. fixtures test hello_world])
+ end
+
+ def with_instance_variables
+ @secret = 'in the sauce'
+ render :file => File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb')
+ end
+
+ def without_file_key
+ render File.join(File.dirname(__FILE__), *%w[.. fixtures test hello_world])
+ end
+
+ def without_file_key_with_instance_variable
+ @secret = 'in the sauce'
+ render File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_ivar.erb')
+ end
+
+ def relative_path
+ @secret = 'in the sauce'
+ render :file => '../fixtures/test/render_file_with_ivar'
+ end
+
+ def relative_path_with_dot
+ @secret = 'in the sauce'
+ render :file => '../fixtures/test/dot.directory/render_file_with_ivar'
+ end
+
+ def pathname
+ @secret = 'in the sauce'
+ render :file => Pathname.new(File.dirname(__FILE__)).join(*%w[.. fixtures test dot.directory render_file_with_ivar.erb])
+ end
+
+ def with_locals
+ path = File.join(File.dirname(__FILE__), '../fixtures/test/render_file_with_locals.erb')
+ render :file => path, :locals => {:secret => 'in the sauce'}
+ end
+
+ def without_file_key_with_locals
+ path = File.expand_path('../fixtures/test/render_file_with_locals.erb')
+ render path, :locals => {:secret => 'in the sauce'}
+ end
+ end
+
+ class TestBasic < SimpleRouteCase
+ testing RenderFile::BasicController
+
+ def setup
+ @old_pwd = Dir.pwd
+ Dir.chdir(File.dirname(__FILE__))
+ end
+
+ def teardown
+ Dir.chdir(@old_pwd)
+ end
+
+ test "rendering simple template" do
+ get :index
+ assert_response "Hello world!"
+ end
+
+ test "rendering template with ivar" do
+ get :with_instance_variables
+ assert_response "The secret is in the sauce\n"
+ end
+
+ test "rendering path without specifying the :file key" do
+ get :without_file_key
+ assert_response "Hello world!"
+ end
+
+ test "rendering path without specifying the :file key with ivar" do
+ get :without_file_key_with_instance_variable
+ assert_response "The secret is in the sauce\n"
+ end
+
+ test "rendering a relative path" do
+ get :relative_path
+ assert_response "The secret is in the sauce\n"
+ end
+
+ test "rendering a relative path with dot" do
+ get :relative_path_with_dot
+ assert_response "The secret is in the sauce\n"
+ end
+
+ test "rendering a Pathname" do
+ get :pathname
+ assert_response "The secret is in the sauce\n"
+ end
+
+ test "rendering file with locals" do
+ get :with_locals
+ assert_response "The secret is in the sauce\n"
+ end
+
+ test "rendering path without specifying the :file key with locals" do
+ get :without_file_key_with_locals
+ assert_response "The secret is in the sauce\n"
+ end
+ end
+
+end \ No newline at end of file
diff --git a/actionpack/test/new_base/render_implicit_action_test.rb b/actionpack/test/new_base/render_implicit_action_test.rb
index 798505b539..2846df48da 100644
--- a/actionpack/test/new_base/render_implicit_action_test.rb
+++ b/actionpack/test/new_base/render_implicit_action_test.rb
@@ -1,16 +1,28 @@
require File.join(File.expand_path(File.dirname(__FILE__)), "test_helper")
-module HappyPath
-
- class RenderImplicitActionController < ActionController::Base2
- # No actions yet, they are implicit
+module RenderImplicitAction
+ class SimpleController < ::ApplicationController
+ self.view_paths = [ActionView::Template::FixturePath.new(
+ "render_implicit_action/simple/hello_world.html.erb" => "Hello world!",
+ "render_implicit_action/simple/hyphen-ated.html.erb" => "Hello hyphen-ated!"
+ )]
+
+ def hello_world() end
end
- class TestRendersActionImplicitly < SimpleRouteCase
-
- test "renders action implicitly" do
- assert true
+ class RenderImplicitActionTest < SimpleRouteCase
+ test "render a simple action with new explicit call to render" do
+ get "/render_implicit_action/simple/hello_world"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
+
+ test "render an action with a missing method and has special characters" do
+ get "/render_implicit_action/simple/hyphen-ated"
+
+ assert_body "Hello hyphen-ated!"
+ assert_status 200
end
-
end
end \ No newline at end of file
diff --git a/actionpack/test/new_base/render_layout_test.rb b/actionpack/test/new_base/render_layout_test.rb
index facf67ea85..f32c60d683 100644
--- a/actionpack/test/new_base/render_layout_test.rb
+++ b/actionpack/test/new_base/render_layout_test.rb
@@ -2,44 +2,100 @@ require File.join(File.expand_path(File.dirname(__FILE__)), "test_helper")
module ControllerLayouts
class ImplicitController < ::ApplicationController
-
- self.view_paths = [ActionView::FixtureTemplate::FixturePath.new(
+ self.view_paths = [ActionView::Template::FixturePath.new(
"layouts/application.html.erb" => "OMG <%= yield %> KTHXBAI",
- "basic.html.erb" => "Hello world!"
+ "layouts/override.html.erb" => "Override! <%= yield %>",
+ "basic.html.erb" => "Hello world!",
+ "controller_layouts/implicit/layout_false.html.erb" => "hai(layout_false.html.erb)"
)]
-
+
def index
render :template => "basic"
end
+
+ def override
+ render :template => "basic", :layout => "override"
+ end
+
+ def layout_false
+ render :layout => false
+ end
+
+ def builder_override
+ end
end
-
- class TestImplicitLayout < SimpleRouteCase
- describe "rendering a normal template, but using the implicit layout"
-
- get "/controller_layouts/implicit/index"
- assert_body "OMG Hello world! KTHXBAI"
- assert_status 200
- end
-
+
class ImplicitNameController < ::ApplicationController
-
- self.view_paths = [ActionView::FixtureTemplate::FixturePath.new(
+ self.view_paths = [ActionView::Template::FixturePath.new(
"layouts/controller_layouts/implicit_name.html.erb" => "OMGIMPLICIT <%= yield %> KTHXBAI",
"basic.html.erb" => "Hello world!"
)]
-
+
def index
render :template => "basic"
end
end
-
- class TestImplicitNamedLayout < SimpleRouteCase
- describe "rendering a normal template, but using an implicit NAMED layout"
-
- get "/controller_layouts/implicit_name/index"
- assert_body "OMGIMPLICIT Hello world! KTHXBAI"
- assert_status 200
+
+ class RenderLayoutTest < SimpleRouteCase
+ test "rendering a normal template, but using the implicit layout" do
+ get "/controller_layouts/implicit/index"
+
+ assert_body "OMG Hello world! KTHXBAI"
+ assert_status 200
+ end
+
+ test "rendering a normal template, but using an implicit NAMED layout" do
+ get "/controller_layouts/implicit_name/index"
+
+ assert_body "OMGIMPLICIT Hello world! KTHXBAI"
+ assert_status 200
+ end
+
+ test "overriding an implicit layout with render :layout option" do
+ get "/controller_layouts/implicit/override"
+ assert_body "Override! Hello world!"
+ end
+
+ end
+
+ class LayoutOptionsTest < SimpleRouteCase
+ testing ControllerLayouts::ImplicitController
+
+ test "rendering with :layout => false leaves out the implicit layout" do
+ get :layout_false
+ assert_response "hai(layout_false.html.erb)"
+ end
+ end
+
+ class MismatchFormatController < ::ApplicationController
+ self.view_paths = [ActionView::Template::FixturePath.new(
+ "layouts/application.html.erb" => "<html><%= yield %></html>",
+ "controller_layouts/mismatch_format/index.js.rjs" => "page[:test].omg",
+ "controller_layouts/mismatch_format/implicit.rjs" => "page[:test].omg"
+ )]
+
+ def explicit
+ render :layout => "application"
+ end
+ end
+
+ class MismatchFormatTest < SimpleRouteCase
+ testing ControllerLayouts::MismatchFormatController
+
+ test "if JS is selected, an HTML template is not also selected" do
+ get :index
+ assert_response "$(\"test\").omg();"
+ end
+
+ test "if JS is implicitly selected, an HTML template is not also selected" do
+ get :implicit
+ assert_response "$(\"test\").omg();"
+ 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
+ end
end
-
-
end \ No newline at end of file
diff --git a/actionpack/test/new_base/render_partial_test.rb b/actionpack/test/new_base/render_partial_test.rb
new file mode 100644
index 0000000000..3a300afe5c
--- /dev/null
+++ b/actionpack/test/new_base/render_partial_test.rb
@@ -0,0 +1,27 @@
+require File.join(File.expand_path(File.dirname(__FILE__)), "test_helper")
+
+module RenderPartial
+
+ class BasicController < ActionController::Base
+
+ self.view_paths = [ActionView::Template::FixturePath.new(
+ "render_partial/basic/_basic.html.erb" => "OMG!",
+ "render_partial/basic/basic.html.erb" => "<%= @test_unchanged = 'goodbye' %><%= render :partial => 'basic' %><%= @test_unchanged %>"
+ )]
+
+ def changing
+ @test_unchanged = 'hello'
+ render :action => "basic"
+ end
+ end
+
+ class TestPartial < SimpleRouteCase
+ testing BasicController
+
+ test "rendering a partial in ActionView doesn't pull the ivars again from the controller" do
+ get :changing
+ assert_response("goodbyeOMG!goodbye")
+ end
+ end
+
+end \ No newline at end of file
diff --git a/actionpack/test/new_base/render_template_test.rb b/actionpack/test/new_base/render_template_test.rb
index c6c0269b40..face5b7571 100644
--- a/actionpack/test/new_base/render_template_test.rb
+++ b/actionpack/test/new_base/render_template_test.rb
@@ -1,133 +1,170 @@
require File.join(File.expand_path(File.dirname(__FILE__)), "test_helper")
-module HappyPath
-
- class RenderTemplateWithoutLayoutController < ActionController::Base2
-
- self.view_paths = [ActionView::FixtureTemplate::FixturePath.new(
- "test/basic.html.erb" => "Hello from basic.html.erb",
- "shared.html.erb" => "Elastica"
+module RenderTemplate
+ class WithoutLayoutController < ActionController::Base
+
+ self.view_paths = [ActionView::Template::FixturePath.new(
+ "test/basic.html.erb" => "Hello from basic.html.erb",
+ "shared.html.erb" => "Elastica",
+ "locals.html.erb" => "The secret is <%= secret %>",
+ "xml_template.xml.builder" => "xml.html do\n xml.p 'Hello'\nend"
)]
- def render_hello_world
+ def index
render :template => "test/basic"
end
-
- def render_hello_world_with_forward_slash
- render :template => "/test/basic"
+
+ def index_without_key
+ render "test/basic"
end
- def render_template_in_top_directory
+ def in_top_directory
render :template => 'shared'
end
- def render_template_in_top_directory_with_slash
+ def in_top_directory_with_slash
render :template => '/shared'
end
- end
-
- class TestTemplateRenderWithoutLayout < SimpleRouteCase
- describe "rendering a normal template with full path without layout"
- get "/happy_path/render_template_without_layout/render_hello_world"
- assert_body "Hello from basic.html.erb"
- assert_status 200
- end
-
- class TestTemplateRenderWithForwardSlash < SimpleRouteCase
- describe "rendering a normal template with full path starting with a leading slash"
+ def in_top_directory_with_slash_without_key
+ render '/shared'
+ end
+
+ def with_locals
+ render :template => "locals", :locals => { :secret => 'area51' }
+ end
- get "/happy_path/render_template_without_layout/render_hello_world_with_forward_slash"
- assert_body "Hello from basic.html.erb"
- assert_status 200
+ def builder_template
+ render :template => "xml_template"
+ end
end
- class TestTemplateRenderInTopDirectory < SimpleRouteCase
- describe "rendering a template not in a subdirectory"
+ class TestWithoutLayout < SimpleRouteCase
+ testing RenderTemplate::WithoutLayoutController
- get "/happy_path/render_template_without_layout/render_template_in_top_directory"
- assert_body "Elastica"
- assert_status 200
- end
-
- class TestTemplateRenderInTopDirectoryWithSlash < SimpleRouteCase
- describe "rendering a template not in a subdirectory with a leading slash"
+ test "rendering a normal template with full path without layout" do
+ get :index
+ assert_response "Hello from basic.html.erb"
+ end
- get "/happy_path/render_template_without_layout/render_template_in_top_directory_with_slash"
- assert_body "Elastica"
- assert_status 200
- end
+ test "rendering a normal template with full path without layout without key" do
+ get :index_without_key
+ assert_response "Hello from basic.html.erb"
+ end
+
+ test "rendering a template not in a subdirectory" do
+ get :in_top_directory
+ assert_response "Elastica"
+ end
+
+ test "rendering a template not in a subdirectory with a leading slash" do
+ get :in_top_directory_with_slash
+ assert_response "Elastica"
+ end
+
+ test "rendering a template not in a subdirectory with a leading slash without key" do
+ get :in_top_directory_with_slash_without_key
+ assert_response "Elastica"
+ end
+
+ test "rendering a template with local variables" do
+ get :with_locals
+ assert_response "The secret is area51"
+ end
- class RenderTemplateWithLayoutController < ::ApplicationController
+ test "rendering a builder template" do
+ get :builder_template
+ assert_response "<html>\n <p>Hello</p>\n</html>\n"
+ end
+ end
- self.view_paths = [ActionView::FixtureTemplate::FixturePath.new(
+ class WithLayoutController < ::ApplicationController
+ self.view_paths = [ActionView::Template::FixturePath.new(
"test/basic.html.erb" => "Hello from basic.html.erb",
"shared.html.erb" => "Elastica",
"layouts/application.html.erb" => "<%= yield %>, I'm here!",
"layouts/greetings.html.erb" => "<%= yield %>, I wish thee well."
)]
- def render_hello_world
+ def index
render :template => "test/basic"
end
- def render_hello_world_with_layout
+ def with_layout
render :template => "test/basic", :layout => true
end
- def render_hello_world_with_layout_false
+ def with_layout_false
render :template => "test/basic", :layout => false
end
- def render_hello_world_with_layout_nil
+ def with_layout_nil
render :template => "test/basic", :layout => nil
end
- def render_hello_world_with_custom_layout
+ def with_custom_layout
render :template => "test/basic", :layout => "greetings"
end
end
- class TestTemplateRenderWithLayout < SimpleRouteCase
- describe "rendering a normal template with full path with layout"
-
- get "/happy_path/render_template_with_layout/render_hello_world"
- assert_body "Hello from basic.html.erb, I'm here!"
- assert_status 200
- end
-
- class TestTemplateRenderWithLayoutTrue < SimpleRouteCase
- describe "rendering a normal template with full path with layout => :true"
-
- get "/happy_path/render_template_with_layout/render_hello_world_with_layout"
- assert_body "Hello from basic.html.erb, I'm here!"
- assert_status 200
- end
-
- class TestTemplateRenderWithLayoutFalse < SimpleRouteCase
- describe "rendering a normal template with full path with layout => :false"
-
- get "/happy_path/render_template_with_layout/render_hello_world_with_layout_false"
- assert_body "Hello from basic.html.erb"
- assert_status 200
- end
-
- class TestTemplateRenderWithLayoutNil < SimpleRouteCase
- describe "rendering a normal template with full path with layout => :nil"
-
- get "/happy_path/render_template_with_layout/render_hello_world_with_layout_nil"
- assert_body "Hello from basic.html.erb"
- assert_status 200
- end
-
- class TestTemplateRenderWithCustomLayout < SimpleRouteCase
- describe "rendering a normal template with full path with layout => 'greetings'"
-
- get "/happy_path/render_template_with_layout/render_hello_world_with_custom_layout"
- assert_body "Hello from basic.html.erb, I wish thee well."
- assert_status 200
+ class TestWithLayout < SimpleRouteCase
+ describe "Rendering with :template using implicit or explicit layout"
+
+ test "rendering with implicit layout" do
+ get "/render_template/with_layout"
+
+ assert_body "Hello from basic.html.erb, I'm here!"
+ assert_status 200
+ end
+
+ test "rendering with layout => :true" do
+ get "/render_template/with_layout/with_layout"
+
+ assert_body "Hello from basic.html.erb, I'm here!"
+ assert_status 200
+ end
+
+ test "rendering with layout => :false" do
+ get "/render_template/with_layout/with_layout_false"
+
+ assert_body "Hello from basic.html.erb"
+ assert_status 200
+ end
+
+ test "rendering with layout => :nil" do
+ get "/render_template/with_layout/with_layout_nil"
+
+ assert_body "Hello from basic.html.erb"
+ assert_status 200
+ end
+
+ test "rendering layout => 'greetings'" do
+ get "/render_template/with_layout/with_custom_layout"
+
+ assert_body "Hello from basic.html.erb, I wish thee well."
+ assert_status 200
+ end
end
-
-
+ module Compatibility
+ class WithoutLayoutController < ActionController::Base
+ self.view_paths = [ActionView::Template::FixturePath.new(
+ "test/basic.html.erb" => "Hello from basic.html.erb",
+ "shared.html.erb" => "Elastica"
+ )]
+
+ def with_forward_slash
+ render :template => "/test/basic"
+ end
+ end
+
+ class TestTemplateRenderWithForwardSlash < SimpleRouteCase
+ test "rendering a normal template with full path starting with a leading slash" do
+ get "/render_template/compatibility/without_layout/with_forward_slash"
+
+ assert_body "Hello from basic.html.erb"
+ assert_status 200
+ end
+ end
+ end
end \ No newline at end of file
diff --git a/actionpack/test/new_base/render_test.rb b/actionpack/test/new_base/render_test.rb
new file mode 100644
index 0000000000..ed3d50fa0b
--- /dev/null
+++ b/actionpack/test/new_base/render_test.rb
@@ -0,0 +1,85 @@
+require File.join(File.expand_path(File.dirname(__FILE__)), "test_helper")
+
+module Render
+ class BlankRenderController < ActionController::Base
+ self.view_paths = [ActionView::Template::FixturePath.new(
+ "render/blank_render/index.html.erb" => "Hello world!",
+ "render/blank_render/access_request.html.erb" => "The request: <%= request.method.to_s.upcase %>",
+ "render/blank_render/access_action_name.html.erb" => "Action Name: <%= action_name %>",
+ "render/blank_render/access_controller_name.html.erb" => "Controller Name: <%= controller_name %>"
+ )]
+
+ def index
+ render
+ end
+
+ def access_request
+ render :action => "access_request"
+ end
+
+ def render_action_name
+ render :action => "access_action_name"
+ end
+
+ private
+
+ def secretz
+ render :text => "FAIL WHALE!"
+ end
+ end
+
+ class DoubleRenderController < ActionController::Base
+ def index
+ render :text => "hello"
+ render :text => "world"
+ end
+ end
+
+ class RenderTest < SimpleRouteCase
+ test "render with blank" do
+ get "/render/blank_render"
+
+ assert_body "Hello world!"
+ assert_status 200
+ end
+
+ test "rendering more than once raises an exception" do
+ assert_raises(AbstractController::DoubleRenderError) do
+ get "/render/double_render", {}, "action_dispatch.show_exceptions" => false
+ end
+ end
+ end
+
+ class TestOnlyRenderPublicActions < SimpleRouteCase
+ describe "Only public methods on actual controllers are callable actions"
+
+ test "raises an exception when a method of Object is called" do
+ assert_raises(AbstractController::ActionNotFound) do
+ get "/render/blank_render/clone", {}, "action_dispatch.show_exceptions" => false
+ end
+ end
+
+ test "raises an exception when a private method is called" do
+ assert_raises(AbstractController::ActionNotFound) do
+ get "/render/blank_render/secretz", {}, "action_dispatch.show_exceptions" => false
+ end
+ end
+ end
+
+ class TestVariousObjectsAvailableInView < SimpleRouteCase
+ test "The request object is accessible in the view" do
+ get "/render/blank_render/access_request"
+ assert_body "The request: GET"
+ end
+
+ test "The action_name is accessible in the view" do
+ get "/render/blank_render/render_action_name"
+ assert_body "Action Name: render_action_name"
+ end
+
+ test "The controller_name is accessible in the view" do
+ get "/render/blank_render/access_controller_name"
+ assert_body "Controller Name: blank_render"
+ end
+ end
+end \ No newline at end of file
diff --git a/actionpack/test/new_base/render_text_test.rb b/actionpack/test/new_base/render_text_test.rb
index a20ca5fb8c..ffc149283b 100644
--- a/actionpack/test/new_base/render_text_test.rb
+++ b/actionpack/test/new_base/render_text_test.rb
@@ -1,144 +1,139 @@
require File.join(File.expand_path(File.dirname(__FILE__)), "test_helper")
-class ApplicationController < ActionController::Base2
-end
-
-module HappyPath
-
- class RenderTextWithoutLayoutsController < ActionController::Base2
- self.view_paths = [ActionView::FixtureTemplate::FixturePath.new]
+module RenderText
+ class SimpleController < ActionController::Base
+ self.view_paths = [ActionView::Template::FixturePath.new]
- def render_hello_world
+ def index
render :text => "hello david"
end
end
-
- class RenderTextWithLayoutsController < ::ApplicationController
- self.view_paths = [ActionView::FixtureTemplate::FixturePath.new(
+
+ class WithLayoutController < ::ApplicationController
+ self.view_paths = [ActionView::Template::FixturePath.new(
"layouts/application.html.erb" => "<%= yield %>, I'm here!",
- "layouts/greetings.html.erb" => "<%= yield %>, I wish thee well."
+ "layouts/greetings.html.erb" => "<%= yield %>, I wish thee well.",
+ "layouts/ivar.html.erb" => "<%= yield %>, <%= @ivar %>"
)]
- def render_hello_world
+ def index
render :text => "hello david"
end
- def render_custom_code
+ def custom_code
render :text => "hello world", :status => 404
end
- def render_with_custom_code_as_string
+ def with_custom_code_as_string
render :text => "hello world", :status => "404 Not Found"
end
- def render_text_with_nil
+ def with_nil
render :text => nil
end
- def render_text_with_nil_and_status
+ def with_nil_and_status
render :text => nil, :status => 403
end
- def render_text_with_false
+ def with_false
render :text => false
end
- def render_text_with_layout
+ def with_layout_true
render :text => "hello world", :layout => true
end
- def render_text_with_layout_false
+ def with_layout_false
render :text => "hello world", :layout => false
end
- def render_text_with_layout_nil
+ def with_layout_nil
render :text => "hello world", :layout => nil
end
- def render_text_with_custom_layout
+ def with_custom_layout
render :text => "hello world", :layout => "greetings"
end
- end
-
- class TestSimpleTextRenderWithNoLayout < SimpleRouteCase
- describe "Rendering text from a action with default options renders the text with the layout"
-
- get "/happy_path/render_text_without_layouts/render_hello_world"
- assert_body "hello david"
- assert_status 200
- end
-
- class TestSimpleTextRenderWithLayout < SimpleRouteCase
- describe "Rendering text from a action with default options renders the text without the layout"
-
- get "/happy_path/render_text_with_layouts/render_hello_world"
- assert_body "hello david"
- assert_status 200
- end
-
- class TestTextRenderWithStatus < SimpleRouteCase
- describe "Rendering text, while also providing a custom status code"
-
- get "/happy_path/render_text_with_layouts/render_custom_code"
- assert_body "hello world"
- assert_status 404
- end
-
- class TestTextRenderWithNil < SimpleRouteCase
- describe "Rendering text with nil returns a single space character"
-
- get "/happy_path/render_text_with_layouts/render_text_with_nil"
- assert_body " "
- assert_status 200
- end
-
- class TestTextRenderWithNilAndStatus < SimpleRouteCase
- describe "Rendering text with nil and custom status code returns a single space character with the status"
-
- get "/happy_path/render_text_with_layouts/render_text_with_nil_and_status"
- assert_body " "
- assert_status 403
- end
-
- class TestTextRenderWithFalse < SimpleRouteCase
- describe "Rendering text with false returns the string 'false'"
-
- get "/happy_path/render_text_with_layouts/render_text_with_false"
- assert_body "false"
- assert_status 200
- end
-
- class TestTextRenderWithLayoutTrue < SimpleRouteCase
- describe "Rendering text with :layout => true"
-
- get "/happy_path/render_text_with_layouts/render_text_with_layout"
- assert_body "hello world, I'm here!"
- assert_status 200
- end
-
- class TestTextRenderWithCustomLayout < SimpleRouteCase
- describe "Rendering text with :layout => 'greetings'"
-
- get "/happy_path/render_text_with_layouts/render_text_with_custom_layout"
- assert_body "hello world, I wish thee well."
- assert_status 200
- end
-
- class TestTextRenderWithLayoutFalse < SimpleRouteCase
- describe "Rendering text with :layout => false"
- get "/happy_path/render_text_with_layouts/render_text_with_layout_false"
- assert_body "hello world"
- assert_status 200
+ def with_ivar_in_layout
+ @ivar = "hello world"
+ render :text => "hello world", :layout => "ivar"
+ end
end
-
- class TestTextRenderWithLayoutNil < SimpleRouteCase
- describe "Rendering text with :layout => nil"
-
- get "/happy_path/render_text_with_layouts/render_text_with_layout_nil"
- assert_body "hello world"
- assert_status 200
+
+ class RenderTextTest < SimpleRouteCase
+ describe "Rendering text using render :text"
+
+ test "rendering text from a action with default options renders the text with the layout" do
+ get "/render_text/simple"
+ assert_body "hello david"
+ assert_status 200
+ end
+
+ test "rendering text from a action with default options renders the text without the layout" do
+ get "/render_text/with_layout"
+
+ assert_body "hello david"
+ assert_status 200
+ end
+
+ test "rendering text, while also providing a custom status code" do
+ get "/render_text/with_layout/custom_code"
+
+ assert_body "hello world"
+ assert_status 404
+ end
+
+ test "rendering text with nil returns an empty body padded for Safari" do
+ get "/render_text/with_layout/with_nil"
+
+ assert_body " "
+ assert_status 200
+ end
+
+ test "Rendering text with nil and custom status code returns an empty body padded for Safari and the status" do
+ get "/render_text/with_layout/with_nil_and_status"
+
+ assert_body " "
+ assert_status 403
+ end
+
+ test "rendering text with false returns the string 'false'" do
+ get "/render_text/with_layout/with_false"
+
+ assert_body "false"
+ assert_status 200
+ end
+
+ test "rendering text with :layout => true" do
+ get "/render_text/with_layout/with_layout_true"
+
+ assert_body "hello world, I'm here!"
+ assert_status 200
+ end
+
+ test "rendering text with :layout => 'greetings'" do
+ get "/render_text/with_layout/with_custom_layout"
+
+ assert_body "hello world, I wish thee well."
+ assert_status 200
+ end
+
+ test "rendering text with :layout => false" do
+ get "/render_text/with_layout/with_layout_false"
+
+ assert_body "hello world"
+ assert_status 200
+ end
+
+ test "rendering text with :layout => nil" do
+ get "/render_text/with_layout/with_layout_nil"
+
+ assert_body "hello world"
+ assert_status 200
+ end
end
end
-ActionController::Base2.app_loaded! \ No newline at end of file
+ActionController::Base.app_loaded!
diff --git a/actionpack/test/new_base/render_xml_test.rb b/actionpack/test/new_base/render_xml_test.rb
new file mode 100644
index 0000000000..e6c40b1533
--- /dev/null
+++ b/actionpack/test/new_base/render_xml_test.rb
@@ -0,0 +1,11 @@
+require File.join(File.expand_path(File.dirname(__FILE__)), "test_helper")
+
+module RenderXml
+
+ # This has no layout and it works
+ class BasicController < ActionController::Base
+ self.view_paths = [ActionView::Template::FixturePath.new(
+ "render_xml/basic/with_render_erb" => "Hello world!"
+ )]
+ end
+end \ No newline at end of file
diff --git a/actionpack/test/new_base/test_helper.rb b/actionpack/test/new_base/test_helper.rb
index d29449ddc1..d92029df7f 100644
--- a/actionpack/test/new_base/test_helper.rb
+++ b/actionpack/test/new_base/test_helper.rb
@@ -5,8 +5,7 @@ $:.unshift(File.dirname(__FILE__) + '/../lib')
require 'test/unit'
require 'active_support'
require 'active_support/test_case'
-require 'action_controller'
-require 'action_view/base'
+require 'action_view'
require 'fixture_template'
begin
@@ -21,118 +20,85 @@ require 'action_controller/abstract'
require 'action_controller/new_base'
require 'pp' # require 'pp' early to prevent hidden_methods from not picking up the pretty-print methods until too late
-require 'rubygems'
-require 'rack/test'
-
-module ActionController
- class Base2 < AbstractBase
- use AbstractController::Callbacks
- use AbstractController::Helpers
- use AbstractController::Logger
-
- use ActionController::HideActions
- use ActionController::UrlFor
- use ActionController::Renderer
- use ActionController::Layouts
-
- def self.inherited(klass)
- ::ActionController::Base2.subclasses << klass.to_s
- super
- end
-
- def self.subclasses
- @subclasses ||= []
- end
-
- def self.app_loaded!
- @subclasses.each do |subclass|
- subclass.constantize._write_layout_method
- end
- end
-
- # append_view_path File.join(File.dirname(__FILE__), '..', 'fixtures')
-
- CORE_METHODS = self.public_instance_methods
+require 'action_controller/testing/process'
+require 'action_controller/testing/integration'
+
+module Rails
+ def self.env
+ x = Object.new
+ def x.test?() true end
+ x
end
end
# Temporary base class
-class Rack::TestCase < ActiveSupport::TestCase
- include Rack::Test::Methods
-
+class Rack::TestCase < ActionController::IntegrationTest
setup do
ActionController::Base.session_options[:key] = "abc"
ActionController::Base.session_options[:secret] = ("*" * 30)
-
- controllers = ActionController::Base2.subclasses.map do |k|
+
+ controllers = ActionController::Base.subclasses.map do |k|
k.underscore.sub(/_controller$/, '')
end
-
+
ActionController::Routing.use_controllers!(controllers)
-
+
# Move into a bootloader
- AbstractController::Base.subclasses.each do |klass|
+ ActionController::Base.subclasses.each do |klass|
klass = klass.constantize
next unless klass < AbstractController::Layouts
klass.class_eval do
_write_layout_method
end
- end
+ end
end
-
+
def app
@app ||= ActionController::Dispatcher.new
end
-
- def self.get(url)
- setup do |test|
- test.get url
+
+ def self.testing(klass = nil)
+ if klass
+ @testing = "/#{klass.name.underscore}".sub!(/_controller$/, '')
+ else
+ @testing
end
end
-
- def assert_body(body)
- assert_equal [body], last_response.body
- end
-
- def self.assert_body(body)
- test "body is set to '#{body}'" do
- assert_body body
+
+ def get(thing, *args)
+ if thing.is_a?(Symbol)
+ super("#{self.class.testing}/#{thing}", *args)
+ else
+ super
end
end
-
+
+ def assert_body(body)
+ assert_equal body, Array.wrap(response.body).join
+ end
+
def assert_status(code)
- assert_equal code, last_response.status
+ assert_equal code, response.status
end
-
- def self.assert_status(code)
- test "status code is set to #{code}" do
- assert_status code
+
+ def assert_response(body, status = 200, headers = {})
+ assert_body body
+ assert_status status
+ headers.each do |header, value|
+ assert_header header, value
end
end
-
+
def assert_content_type(type)
- assert_equal type, last_response.headers["Content-Type"]
- end
-
- def self.assert_content_type(type)
- test "content type is set to #{type}" do
- assert_content_type(type)
- end
+ assert_equal type, response.headers["Content-Type"]
end
-
+
def assert_header(name, value)
- assert_equal value, last_response.headers[name]
- end
-
- def self.assert_header(name, value)
- test "'#{name}' header is set to #{value.inspect}" do
- assert_header(name, value)
- end
+ assert_equal value, response.headers[name]
end
-
end
-class ::ApplicationController < ActionController::Base2
+class ::ApplicationController < ActionController::Base
end
class SimpleRouteCase < Rack::TestCase
diff --git a/actionpack/test/template/body_parts_test.rb b/actionpack/test/template/body_parts_test.rb
index 4c82b75cdc..4e7aa63f96 100644
--- a/actionpack/test/template/body_parts_test.rb
+++ b/actionpack/test/template/body_parts_test.rb
@@ -4,9 +4,12 @@ class BodyPartsTest < ActionController::TestCase
RENDERINGS = [Object.new, Object.new, Object.new]
class TestController < ActionController::Base
+ def performed?
+ defined?(ActionController::Http) ? true : super
+ end
def index
RENDERINGS.each do |rendering|
- response.template.punctuate_body! rendering
+ @template.punctuate_body! rendering
end
@performed_render = true
end
@@ -16,7 +19,11 @@ class BodyPartsTest < ActionController::TestCase
def test_body_parts
get :index
- assert_equal RENDERINGS, @response.body_parts
+ pending(:old_base) do
+ # TestProcess buffers body_parts into body
+ # TODO: Rewrite test w/o going through process
+ assert_equal RENDERINGS, @response.body_parts
+ end
assert_equal RENDERINGS.join, @response.body
end
end
diff --git a/actionpack/test/template/compiled_templates_test.rb b/actionpack/test/template/compiled_templates_test.rb
index c75e29ed9a..b29b03f99d 100644
--- a/actionpack/test/template/compiled_templates_test.rb
+++ b/actionpack/test/template/compiled_templates_test.rb
@@ -5,37 +5,13 @@ class CompiledTemplatesTest < Test::Unit::TestCase
def setup
@compiled_templates = ActionView::Base::CompiledTemplates
@compiled_templates.instance_methods.each do |m|
- @compiled_templates.send(:remove_method, m) if m =~ /^_run_/
+ @compiled_templates.send(:remove_method, m) if m =~ /^_render_template_/
end
end
-
- def test_template_gets_compiled
- assert_equal 0, @compiled_templates.instance_methods.size
- assert_equal "Hello world!", render(:file => "test/hello_world.erb")
- assert_equal 1, @compiled_templates.instance_methods.size
- end
-
+
def test_template_gets_recompiled_when_using_different_keys_in_local_assigns
- assert_equal 0, @compiled_templates.instance_methods.size
- assert_equal "Hello world!", render(:file => "test/hello_world.erb")
- assert_equal "Hello world!", render(:file => "test/hello_world.erb", :locals => {:foo => "bar"})
- assert_equal 2, @compiled_templates.instance_methods.size
- end
-
- def test_compiled_template_will_not_be_recompiled_when_rendered_with_identical_local_assigns
- assert_equal 0, @compiled_templates.instance_methods.size
- assert_equal "Hello world!", render(:file => "test/hello_world.erb")
- ActionView::Template.any_instance.expects(:compile!).never
- assert_equal "Hello world!", render(:file => "test/hello_world.erb")
- end
-
- def test_compiled_template_will_always_be_recompiled_when_template_is_not_cached
- ActionView::Template.any_instance.expects(:recompile?).times(3).returns(true)
- assert_equal 0, @compiled_templates.instance_methods.size
- assert_equal "Hello world!", render(:file => "#{FIXTURE_LOAD_PATH}/test/hello_world.erb")
- ActionView::Template.any_instance.expects(:compile!).times(3)
- 3.times { assert_equal "Hello world!", render(:file => "#{FIXTURE_LOAD_PATH}/test/hello_world.erb") }
- assert_equal 1, @compiled_templates.instance_methods.size
+ assert_equal "one", render(:file => "test/render_file_with_locals_and_default.erb")
+ assert_equal "two", render(:file => "test/render_file_with_locals_and_default.erb", :locals => { :secret => "two" })
end
def test_template_changes_are_not_reflected_with_cached_templates
@@ -61,14 +37,12 @@ class CompiledTemplatesTest < Test::Unit::TestCase
def render_with_cache(*args)
view_paths = ActionController::Base.view_paths
- assert_equal ActionView::Template::FileSystemPath, view_paths.first.class
ActionView::Base.new(view_paths, {}).render(*args)
end
def render_without_cache(*args)
- path = ActionView::Template::FileSystemPath.new(FIXTURE_LOAD_PATH)
+ path = ActionView::Template::FileSystemPathWithFallback.new(FIXTURE_LOAD_PATH)
view_paths = ActionView::Base.process_view_paths(path)
- assert_equal ActionView::Template::FileSystemPath, view_paths.first.class
ActionView::Base.new(view_paths, {}).render(*args)
end
diff --git a/actionpack/test/template/form_options_helper_test.rb b/actionpack/test/template/form_options_helper_test.rb
index 78db87971b..73624406be 100644
--- a/actionpack/test/template/form_options_helper_test.rb
+++ b/actionpack/test/template/form_options_helper_test.rb
@@ -80,6 +80,14 @@ class FormOptionsHelperTest < ActionView::TestCase
)
end
+ def test_string_options_for_select
+ options = "<option value=\"Denmark\">Denmark</option><option value=\"USA\">USA</option><option value=\"Sweden\">Sweden</option>"
+ assert_dom_equal(
+ options,
+ options_for_select(options)
+ )
+ end
+
def test_array_options_for_select
assert_dom_equal(
"<option value=\"&lt;Denmark&gt;\">&lt;Denmark&gt;</option>\n<option value=\"USA\">USA</option>\n<option value=\"Sweden\">Sweden</option>",
@@ -324,6 +332,20 @@ class FormOptionsHelperTest < ActionView::TestCase
)
end
+ def test_select_under_fields_for_with_string_and_given_prompt
+ @post = Post.new
+ options = "<option value=\"abe\">abe</option><option value=\"mus\">mus</option><option value=\"hest\">hest</option>"
+
+ fields_for :post, @post do |f|
+ concat f.select(:category, options, :prompt => 'The prompt')
+ end
+
+ assert_dom_equal(
+ "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">The prompt</option>\n#{options}</select>",
+ output_buffer
+ )
+ end
+
def test_select_with_blank
@post = Post.new
@post.category = "<mus>"
diff --git a/actionpack/test/template/javascript_helper_test.rb b/actionpack/test/template/javascript_helper_test.rb
index f9bc92c7c9..8caabfc3e1 100644
--- a/actionpack/test/template/javascript_helper_test.rb
+++ b/actionpack/test/template/javascript_helper_test.rb
@@ -3,6 +3,8 @@ require 'abstract_unit'
class JavaScriptHelperTest < ActionView::TestCase
tests ActionView::Helpers::JavaScriptHelper
+ def _evaluate_assigns_and_ivars() end
+
attr_accessor :formats, :output_buffer
def setup
@@ -10,6 +12,8 @@ class JavaScriptHelperTest < ActionView::TestCase
@template = self
end
+ def _evaluate_assigns_and_ivars() end
+
def test_escape_javascript
assert_equal '', escape_javascript(nil)
assert_equal %(This \\"thing\\" is really\\n netos\\'), escape_javascript(%(This "thing" is really\n netos'))
diff --git a/actionpack/test/template/number_helper_test.rb b/actionpack/test/template/number_helper_test.rb
index 29cb60fd73..b6542ef29d 100644
--- a/actionpack/test/template/number_helper_test.rb
+++ b/actionpack/test/template/number_helper_test.rb
@@ -118,6 +118,10 @@ class NumberHelperTest < ActionView::TestCase
assert_equal '1.01 KB', number_to_human_size(1.0123.kilobytes, :precision => 2)
assert_equal '1.01 KB', number_to_human_size(1.0100.kilobytes, :precision => 4)
assert_equal '10 KB', number_to_human_size(10.000.kilobytes, :precision => 4)
+ assert_equal '1 TB', number_to_human_size(1234567890123, :precision => 0)
+ assert_equal '500 MB', number_to_human_size(524288000, :precision=>0)
+ assert_equal '40 KB', number_to_human_size(41010, :precision => 0)
+ assert_equal '40 KB', number_to_human_size(41100, :precision => 0)
end
def test_number_to_human_size_with_custom_delimiter_and_separator
diff --git a/actionpack/test/template/output_buffer_test.rb b/actionpack/test/template/output_buffer_test.rb
index 6d8eab63dc..36bbaf9099 100644
--- a/actionpack/test/template/output_buffer_test.rb
+++ b/actionpack/test/template/output_buffer_test.rb
@@ -9,27 +9,52 @@ class OutputBufferTest < ActionController::TestCase
tests TestController
- def test_flush_output_buffer
- # Start with the default body parts
+ def setup
get :index
- assert_equal ['foo'], @response.body_parts
- assert_nil @response.template.output_buffer
-
- # Nil output buffer is skipped
- @response.template.flush_output_buffer
- assert_nil @response.template.output_buffer
- assert_equal ['foo'], @response.body_parts
-
- # Empty output buffer is skipped
- @response.template.output_buffer = ''
- @response.template.flush_output_buffer
- assert_equal '', @response.template.output_buffer
- assert_equal ['foo'], @response.body_parts
-
- # Flushing appends the output buffer to the body parts
- @response.template.output_buffer = 'bar'
- @response.template.flush_output_buffer
- assert_equal '', @response.template.output_buffer
- assert_equal ['foo', 'bar'], @response.body_parts
+ assert_equal ['foo'], body_parts
end
+
+ test 'output buffer is nil after rendering' do
+ assert_nil output_buffer
+ end
+
+ test 'flushing ignores nil output buffer' do
+ @controller.template.flush_output_buffer
+ assert_nil output_buffer
+ assert_equal ['foo'], body_parts
+ end
+
+ test 'flushing ignores empty output buffer' do
+ @controller.template.output_buffer = ''
+ @controller.template.flush_output_buffer
+ assert_equal '', output_buffer
+ assert_equal ['foo'], body_parts
+ end
+
+ test 'flushing appends the output buffer to the body parts' do
+ @controller.template.output_buffer = 'bar'
+ @controller.template.flush_output_buffer
+ assert_equal '', output_buffer
+ 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)
+ @controller.template.output_buffer = original_buffer
+ @controller.template.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
+ end
+
+ protected
+ def output_buffer
+ @controller.template.output_buffer
+ end
+
+ def body_parts
+ @controller.template.response.body_parts
+ end
end
diff --git a/actionpack/test/template/prototype_helper_test.rb b/actionpack/test/template/prototype_helper_test.rb
index cd6ee6ea11..f9f418aec9 100644
--- a/actionpack/test/template/prototype_helper_test.rb
+++ b/actionpack/test/template/prototype_helper_test.rb
@@ -61,6 +61,8 @@ class PrototypeHelperBaseTest < ActionView::TestCase
end
class PrototypeHelperTest < PrototypeHelperBaseTest
+ def _evaluate_assigns_and_ivars() end
+
def setup
@record = @author = Author.new
@article = Article.new
@@ -304,6 +306,8 @@ class JavaScriptGeneratorTest < PrototypeHelperBaseTest
@generator = create_generator
end
+ def _evaluate_assigns_and_ivars() end
+
def test_insert_html_with_string
assert_equal 'Element.insert("element", { top: "\\u003Cp\\u003EThis is a test\\u003C/p\\u003E" });',
@generator.insert_html(:top, 'element', '<p>This is a test</p>')
@@ -328,28 +332,28 @@ class JavaScriptGeneratorTest < PrototypeHelperBaseTest
def test_remove
assert_equal 'Element.remove("foo");',
@generator.remove('foo')
- assert_equal '["foo", "bar", "baz"].each(Element.remove);',
+ assert_equal '["foo","bar","baz"].each(Element.remove);',
@generator.remove('foo', 'bar', 'baz')
end
def test_show
assert_equal 'Element.show("foo");',
@generator.show('foo')
- assert_equal '["foo", "bar", "baz"].each(Element.show);',
+ assert_equal '["foo","bar","baz"].each(Element.show);',
@generator.show('foo', 'bar', 'baz')
end
def test_hide
assert_equal 'Element.hide("foo");',
@generator.hide('foo')
- assert_equal '["foo", "bar", "baz"].each(Element.hide);',
+ assert_equal '["foo","bar","baz"].each(Element.hide);',
@generator.hide('foo', 'bar', 'baz')
end
def test_toggle
assert_equal 'Element.toggle("foo");',
@generator.toggle('foo')
- assert_equal '["foo", "bar", "baz"].each(Element.toggle);',
+ assert_equal '["foo","bar","baz"].each(Element.toggle);',
@generator.toggle('foo', 'bar', 'baz')
end
@@ -386,7 +390,7 @@ class JavaScriptGeneratorTest < PrototypeHelperBaseTest
assert_equal <<-EOS.chomp, @generator.to_s
Element.insert("element", { top: "\\u003Cp\\u003EThis is a test\\u003C/p\\u003E" });
Element.insert("element", { bottom: "\\u003Cp\\u003EThis is a test\\u003C/p\\u003E" });
-["foo", "bar"].each(Element.remove);
+["foo","bar"].each(Element.remove);
Element.update("baz", "\\u003Cp\\u003EThis is a test\\u003C/p\\u003E");
EOS
end
@@ -555,8 +559,8 @@ return (value.className == "welcome");
end
assert_equal <<-EOS.strip, @generator.to_s
-var a = [1, 2, 3].zip([4, 5, 6], [7, 8, 9]);
-var b = [1, 2, 3].zip([4, 5, 6], [7, 8, 9], function(array) {
+var a = [1, 2, 3].zip([4,5,6], [7,8,9]);
+var b = [1, 2, 3].zip([4,5,6], [7,8,9], function(array) {
return array.reverse();
});
EOS
@@ -607,7 +611,7 @@ return value.reverse();
def test_literal
literal = @generator.literal("function() {}")
- assert_equal "function() {}", literal.to_json
+ assert_equal "function() {}", ActiveSupport::JSON.encode(literal)
assert_equal "", @generator.to_s
end
diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb
index 8843f6fdd7..a56d7aee75 100644
--- a/actionpack/test/template/render_test.rb
+++ b/actionpack/test/template/render_test.rb
@@ -29,23 +29,19 @@ module RenderTestCases
end
def test_render_file_with_localization
- pending do
- begin
- old_locale = I18n.locale
- I18n.locale = :da
- assert_equal "Hey verden", @view.render(:file => "test/hello_world")
- ensure
- I18n.locale = old_locale
- end
+ begin
+ old_locale = I18n.locale
+ I18n.locale = :da
+ assert_equal "Hey verden", @view.render(:file => "test/hello_world")
+ ensure
+ I18n.locale = old_locale
end
end
def test_render_file_with_dashed_locale
old_locale = I18n.locale
- pending do
- I18n.locale = :"pt-BR"
- assert_equal "Ola mundo", @view.render(:file => "test/hello_world")
- end
+ I18n.locale = :"pt-BR"
+ assert_equal "Ola mundo", @view.render(:file => "test/hello_world")
ensure
I18n.locale = old_locale
end
@@ -95,10 +91,6 @@ module RenderTestCases
assert_equal "The secret is in the sauce\n", @view.render(:file => "test/dot.directory/render_file_with_ivar")
end
- def test_render_has_access_current_template
- assert_equal "test/template.erb", @view.render(:file => "test/template.erb")
- end
-
def test_render_update
# TODO: You should not have to stub out template because template is self!
@view.instance_variable_set(:@template, @view)
@@ -244,10 +236,6 @@ module RenderTestCases
end
end
- def test_template_with_malformed_template_handler_is_reachable_through_its_exact_filename
- assert_equal "Don't render me!", @view.render(:file => 'test/malformed/malformed.html.erb~')
- end
-
def test_render_with_layout
assert_equal %(<title></title>\nHello world!\n),
@view.render(:file => "test/hello_world.erb", :layout => "layouts/yield")
@@ -261,7 +249,7 @@ module RenderTestCases
if '1.9'.respond_to?(:force_encoding)
def test_render_utf8_template
result = @view.render(:file => "test/utf8.html.erb", :layouts => "layouts/yield")
- assert_equal "Русский текст\n日本語のテキスト", result
+ assert_equal "Русский текст\nUTF-8\nUTF-8\nUTF-8\n", result
assert_equal Encoding::UTF_8, result.encoding
end
end
@@ -273,7 +261,7 @@ class CachedViewRenderTest < ActiveSupport::TestCase
# Ensure view path cache is primed
def setup
view_paths = ActionController::Base.view_paths
- assert_equal ActionView::Template::FileSystemPath, view_paths.first.class
+ assert_equal ActionView::Template::FileSystemPathWithFallback, view_paths.first.class
setup_view(view_paths)
end
end
@@ -284,9 +272,9 @@ class LazyViewRenderTest < ActiveSupport::TestCase
# Test the same thing as above, but make sure the view path
# is not eager loaded
def setup
- path = ActionView::Template::FileSystemPath.new(FIXTURE_LOAD_PATH)
+ path = ActionView::Template::FileSystemPathWithFallback.new(FIXTURE_LOAD_PATH)
view_paths = ActionView::Base.process_view_paths(path)
- assert_equal ActionView::Template::FileSystemPath, view_paths.first.class
+ assert_equal ActionView::Template::FileSystemPathWithFallback, view_paths.first.class
setup_view(view_paths)
end
end
diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb
index be7163888e..706b5085f4 100644
--- a/actionpack/test/template/text_helper_test.rb
+++ b/actionpack/test/template/text_helper_test.rb
@@ -49,6 +49,9 @@ class TextHelperTest < ActionView::TestCase
assert_equal "This is a string that wil[...]", truncate("This is a string that will go longer then the default truncate length of 30", :omission => "[...]")
assert_equal "Hello W...", truncate("Hello World!", :length => 10)
assert_equal "Hello[...]", truncate("Hello World!", :omission => "[...]", :length => 10)
+ assert_equal "Hello[...]", truncate("Hello Big World!", :omission => "[...]", :length => 13, :separator => ' ')
+ assert_equal "Hello Big[...]", truncate("Hello Big World!", :omission => "[...]", :length => 14, :separator => ' ')
+ assert_equal "Hello Big[...]", truncate("Hello Big World!", :omission => "[...]", :length => 15, :separator => ' ')
end
if RUBY_VERSION < '1.9.0'
@@ -401,6 +404,13 @@ class TextHelperTest < ActionView::TestCase
auto_link("Welcome to my new blog at http://www.myblog.com/. Please e-mail me at me@email.com.",
:link => :all, :html => { :class => "menu", :target => "_blank" })
end
+
+ def test_auto_link_with_multiple_trailing_punctuations
+ url = "http://youtube.com"
+ url_result = generate_result(url)
+ assert_equal url_result, auto_link(url)
+ assert_equal "(link: #{url_result}).", auto_link("(link: #{url}).")
+ end
def test_cycle_class
value = Cycle.new("one", 2, "3")