diff options
Diffstat (limited to 'actionview/test')
65 files changed, 1010 insertions, 610 deletions
diff --git a/actionview/test/abstract_unit.rb b/actionview/test/abstract_unit.rb index 7096d588b6..12870acaa6 100644 --- a/actionview/test/abstract_unit.rb +++ b/actionview/test/abstract_unit.rb @@ -16,6 +16,7 @@ silence_warnings do end require 'active_support/testing/autorun' +require 'active_support/testing/method_call_assertions' require 'action_controller' require 'action_view' require 'action_view/testing/resolvers' @@ -46,23 +47,9 @@ I18n.enforce_available_locales = false # 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 +ORIGINAL_LOCALES = I18n.available_locales.map(&:to_s).sort FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures') -FIXTURES = Pathname.new(FIXTURE_LOAD_PATH) - -module RackTestUtils - def body_to_string(body) - if body.respond_to?(:each) - str = "" - body.each {|s| str << s } - str - else - body - end - end - extend self -end module RenderERBUtils def view @@ -161,13 +148,13 @@ class ActionDispatch::IntegrationTest < ActiveSupport::TestCase def self.build_app(routes = nil) RoutedRackApp.new(routes || ActionDispatch::Routing::RouteSet.new) do |middleware| - middleware.use "ActionDispatch::ShowExceptions", ActionDispatch::PublicExceptions.new("#{FIXTURE_LOAD_PATH}/public") - middleware.use "ActionDispatch::DebugExceptions" - middleware.use "ActionDispatch::Callbacks" - middleware.use "ActionDispatch::ParamsParser" - middleware.use "ActionDispatch::Cookies" - middleware.use "ActionDispatch::Flash" - middleware.use "Rack::Head" + middleware.use ActionDispatch::ShowExceptions, ActionDispatch::PublicExceptions.new("#{FIXTURE_LOAD_PATH}/public") + middleware.use ActionDispatch::DebugExceptions + middleware.use ActionDispatch::Callbacks + middleware.use ActionDispatch::ParamsParser + middleware.use ActionDispatch::Cookies + middleware.use ActionDispatch::Flash + middleware.use Rack::Head yield(middleware) if block_given? end end @@ -225,50 +212,7 @@ class ActionDispatch::IntegrationTest < ActiveSupport::TestCase end end -# Temporary base class -class Rack::TestCase < ActionDispatch::IntegrationTest - def self.testing(klass = nil) - if klass - @testing = "/#{klass.name.underscore}".sub!(/_controller$/, '') - else - @testing - end - end - - 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(response.body).join - end - - def assert_status(code) - assert_equal code, response.status - end - - 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, response.headers["Content-Type"] - end - - def assert_header(name, value) - assert_equal value, response.headers[name] - end -end - -ActionView::RoutingUrlFor.send(:include, ActionDispatch::Routing::UrlFor) +ActionView::RoutingUrlFor.include(ActionDispatch::Routing::UrlFor) module ActionController class Base @@ -338,8 +282,6 @@ def jruby_skip(message = '') end require 'mocha/setup' # FIXME: stop using mocha - -# FIXME: we have tests that depend on run order, we should fix that and -# remove this method call. -require 'active_support/test_case' -ActiveSupport::TestCase.test_order = :sorted +class ActiveSupport::TestCase + include ActiveSupport::Testing::MethodCallAssertions +end diff --git a/actionview/test/actionpack/abstract/abstract_controller_test.rb b/actionview/test/actionpack/abstract/abstract_controller_test.rb index e653b12d32..490932fef0 100644 --- a/actionview/test/actionpack/abstract/abstract_controller_test.rb +++ b/actionview/test/actionpack/abstract/abstract_controller_test.rb @@ -168,7 +168,7 @@ module AbstractController end end - class OverridingLocalPrefixesTest < ActiveSupport::TestCase # TODO: remove me in 5.0/4.3. + class OverridingLocalPrefixesTest < ActiveSupport::TestCase test "overriding .local_prefixes adds prefix" do @controller = OverridingLocalPrefixes.new @controller.process(:index) @@ -182,22 +182,6 @@ module AbstractController end end - class DeprecatedParentPrefixes < OverridingLocalPrefixes - def self.parent_prefixes - ["abstract_controller/testing/me3"] - end - end - - class DeprecatedParentPrefixesTest < ActiveSupport::TestCase # TODO: remove me in 5.0/4.3. - test "overriding .parent_prefixes is deprecated" do - @controller = DeprecatedParentPrefixes.new - assert_deprecated do - @controller.process(:index) - end - assert_equal "Hello from me3/index.erb", @controller.response_body - end - end - # Test rendering with layouts # ==== # self._layout is used when defined diff --git a/actionview/test/actionpack/abstract/layouts_test.rb b/actionview/test/actionpack/abstract/layouts_test.rb index a6786d9b6b..80bc665b0a 100644 --- a/actionview/test/actionpack/abstract/layouts_test.rb +++ b/actionview/test/actionpack/abstract/layouts_test.rb @@ -52,7 +52,7 @@ module AbstractControllerTests end def overwrite_skip - render :text => "Hello text!" + render plain: "Hello text!" end end @@ -371,7 +371,7 @@ module AbstractControllerTests test "layout for anonymous controller" do klass = Class.new(WithString) do def index - render :text => 'index', :layout => true + render plain: 'index', layout: true end end diff --git a/actionview/test/actionpack/abstract/render_test.rb b/actionview/test/actionpack/abstract/render_test.rb index d09f91c1e2..e5721d6416 100644 --- a/actionview/test/actionpack/abstract/render_test.rb +++ b/actionview/test/actionpack/abstract/render_test.rb @@ -1,4 +1,5 @@ require 'abstract_unit' +require 'active_support/deprecation' module AbstractController module Testing @@ -33,7 +34,7 @@ module AbstractController end def text - render :text => "With Text" + render plain: "With Text" end def default diff --git a/actionview/test/actionpack/abstract/views/abstract_controller/testing/me5/index.erb b/actionview/test/actionpack/abstract/views/abstract_controller/testing/me5/index.erb deleted file mode 100644 index 84d0b7417e..0000000000 --- a/actionview/test/actionpack/abstract/views/abstract_controller/testing/me5/index.erb +++ /dev/null @@ -1 +0,0 @@ -Hello from me5/index.erb
\ No newline at end of file diff --git a/actionview/test/actionpack/controller/layout_test.rb b/actionview/test/actionpack/controller/layout_test.rb index bd345fe873..64bc4c41d6 100644 --- a/actionview/test/actionpack/controller/layout_test.rb +++ b/actionview/test/actionpack/controller/layout_test.rb @@ -1,5 +1,4 @@ require 'abstract_unit' -require 'rbconfig' require 'active_support/core_ext/array/extract_options' # The view_paths array must be set on Base and not LayoutTest so that LayoutTest's inherited @@ -150,75 +149,75 @@ class LayoutSetInResponseTest < ActionController::TestCase def test_layout_set_when_using_default_layout @controller = DefaultLayoutController.new get :hello - assert_template :layout => "layouts/layout_test" + assert_includes @response.body, 'layout_test.erb' end def test_layout_set_when_using_streaming_layout @controller = StreamingLayoutController.new get :hello - assert_template :hello + assert_includes @response.body, 'layout_test.erb' end def test_layout_set_when_set_in_controller @controller = HasOwnLayoutController.new get :hello - assert_template :layout => "layouts/item" + assert_includes @response.body, 'item.erb' end def test_layout_symbol_set_in_controller_returning_nil_falls_back_to_default @controller = HasNilLayoutSymbol.new get :hello - assert_template layout: "layouts/layout_test" + assert_includes @response.body, 'layout_test.erb' end def test_layout_proc_set_in_controller_returning_nil_falls_back_to_default @controller = HasNilLayoutProc.new get :hello - assert_template layout: "layouts/layout_test" + assert_includes @response.body, 'layout_test.erb' end def test_layout_only_exception_when_included @controller = OnlyLayoutController.new get :hello - assert_template :layout => "layouts/item" + assert_includes @response.body, 'item.erb' end def test_layout_only_exception_when_excepted @controller = OnlyLayoutController.new get :goodbye - assert !@response.body.include?("item.erb"), "#{@response.body.inspect} included 'item.erb'" + assert_not_includes @response.body, 'item.erb' end def test_layout_except_exception_when_included @controller = ExceptLayoutController.new get :hello - assert_template :layout => "layouts/item" + assert_includes @response.body, 'item.erb' end def test_layout_except_exception_when_excepted @controller = ExceptLayoutController.new get :goodbye - assert !@response.body.include?("item.erb"), "#{@response.body.inspect} included 'item.erb'" + assert_not_includes @response.body, 'item.erb' end def test_layout_set_when_using_render with_template_handler :mab, lambda { |template| template.source.inspect } do @controller = SetsLayoutInRenderController.new get :hello - assert_template :layout => "layouts/third_party_template_library" + assert_includes @response.body, 'layouts/third_party_template_library.mab' end end def test_layout_is_not_set_when_none_rendered @controller = RendersNoLayoutController.new get :hello - assert_template :layout => nil + assert_equal 'hello.erb', @response.body end def test_layout_is_picked_from_the_controller_instances_view_path @controller = PrependsViewPathController.new get :hello - assert_template :layout => /layouts\/alt/ + assert_includes @response.body, 'alt.erb' end def test_absolute_pathed_layout @@ -263,7 +262,7 @@ unless RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ @controller = LayoutSymlinkedTest.new get :hello assert_response 200 - assert_template :layout => "layouts/symlinked/symlinked_layout" + assert_includes @response.body, 'This is my layout' end end end diff --git a/actionview/test/actionpack/controller/render_test.rb b/actionview/test/actionpack/controller/render_test.rb index 563caee8a2..8d048ddbcb 100644 --- a/actionview/test/actionpack/controller/render_test.rb +++ b/actionview/test/actionpack/controller/render_test.rb @@ -1,5 +1,5 @@ require 'abstract_unit' -require "active_model" +require 'active_model' class ApplicationController < ActionController::Base self.view_paths = File.join(FIXTURE_LOAD_PATH, "actionpack") @@ -31,6 +31,10 @@ class Customer < Struct.new(:name, :id) def persisted? id.present? end + + def cache_key + name.to_s + end end module Quiz @@ -117,7 +121,7 @@ class TestController < ApplicationController # :ported: def render_hello_world_from_variable @person = "david" - render :text => "hello #{@person}" + render plain: "hello #{@person}" end # :ported: @@ -139,13 +143,13 @@ class TestController < ApplicationController # :ported: def render_text_hello_world - render :text => "hello world" + render plain: "hello world" end # :ported: def render_text_hello_world_with_layout @variable_for_layout = ", I am here!" - render :text => "hello world", :layout => true + render plain: "hello world", :layout => true end def hello_world_with_layout_false @@ -208,26 +212,26 @@ class TestController < ApplicationController # :ported: def render_custom_code - render :text => "hello world", :status => 404 + render plain: "hello world", :status => 404 end # :ported: def render_text_with_nil - render :text => nil + render plain: nil end # :ported: def render_text_with_false - render :text => false + render plain: false end def render_text_with_resource - render :text => Customer.new("David") + render plain: Customer.new("David") end # :ported: def render_nothing_with_appendix - render :text => "appended" + render plain: "appended" end # This test is testing 3 things: @@ -258,7 +262,7 @@ class TestController < ApplicationController # :ported: def blank_response - render :text => ' ' + render plain: ' ' end # :ported: @@ -290,7 +294,7 @@ class TestController < ApplicationController def hello_in_a_string @customers = [ Customer.new("david"), Customer.new("mary") ] - render :text => "How's there? " + render_to_string(:template => "test/list") + render plain: "How's there? " + render_to_string(:template => "test/list") end def accessing_params_in_template @@ -353,12 +357,12 @@ class TestController < ApplicationController end def rendering_nothing_on_layout - render :nothing => true + head :ok end def render_to_string_with_assigns @before = "i'm before the render" - render_to_string :text => "foo" + render_to_string plain: "foo" @after = "i'm after the render" render :template => "test/hello_world" end @@ -405,8 +409,8 @@ class TestController < ApplicationController # :ported: def double_render - render :text => "hello" - render :text => "world" + render plain: "hello" + render plain: "world" end def double_redirect @@ -415,13 +419,13 @@ class TestController < ApplicationController end def render_and_redirect - render :text => "hello" + render plain: "hello" redirect_to :action => "double_render" end def render_to_string_and_render - @stuff = render_to_string :text => "here is some cached stuff" - render :text => "Hi web users! #{@stuff}" + @stuff = render_to_string plain: "here is some cached stuff" + render plain: "Hi web users! #{@stuff}" end def render_to_string_with_inline_and_render @@ -450,7 +454,11 @@ class TestController < ApplicationController # :addressed: def render_text_with_assigns @hello = "world" - render :text => "foo" + render plain: "foo" + end + + def render_with_assigns_option + render inline: '<%= @hello %>', assigns: { hello: "world" } end def yield_content_for @@ -459,7 +467,7 @@ class TestController < ApplicationController def render_content_type_from_body response.content_type = Mime::RSS - render :text => "hello world!" + render body: "hello world!" end def render_using_layout_around_block @@ -675,20 +683,19 @@ class RenderTest < ActionController::TestCase get :hello_world assert_response 200 assert_response :success - assert_template "test/hello_world" 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' + assert_equal "hyphen-ated.erb", @response.body end # :ported: def test_render get :render_hello_world - assert_template "test/hello_world" + assert_equal "Hello world!", @response.body end def test_line_offset @@ -704,20 +711,18 @@ class RenderTest < ActionController::TestCase # :ported: compatibility def test_render_with_forward_slash get :render_hello_world_with_forward_slash - assert_template "test/hello_world" + assert_equal "Hello world!", @response.body 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 @@ -735,7 +740,7 @@ class RenderTest < ActionController::TestCase # :ported: def test_render_action get :render_action_hello_world - assert_template "test/hello_world" + assert_equal "Hello world!", @response.body end def test_render_action_upcased @@ -748,13 +753,12 @@ class RenderTest < ActionController::TestCase 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" + assert_equal "Hello world!", @response.body end # :ported: @@ -766,7 +770,7 @@ class RenderTest < ActionController::TestCase # :ported: def test_do_with_render_text_and_layout get :render_text_hello_world_with_layout - assert_equal "<html>hello world, I am here!</html>", @response.body + assert_equal "{{hello world, I am here!}}\n", @response.body end # :ported: @@ -857,12 +861,12 @@ class RenderTest < ActionController::TestCase # :ported: def test_attempt_to_access_object_method - assert_raise(AbstractController::ActionNotFound, "No action responded to [clone]") { get :clone } + assert_raise(AbstractController::ActionNotFound) { get :clone } end # :ported: def test_private_methods - assert_raise(AbstractController::ActionNotFound, "No action responded to [determine_layout]") { get :determine_layout } + assert_raise(AbstractController::ActionNotFound) { get :determine_layout } end # :ported: @@ -942,7 +946,7 @@ class RenderTest < ActionController::TestCase def test_render_to_string_inline get :render_to_string_with_inline_and_render - assert_template "test/hello_world" + assert_equal 'Hello world!', @response.body end # :ported: @@ -953,23 +957,23 @@ class RenderTest < ActionController::TestCase end def test_accessing_params_in_template - get :accessing_params_in_template, :name => "David" + get :accessing_params_in_template, params: { name: "David" } assert_equal "Hello: David", @response.body end def test_accessing_local_assigns_in_inline_template - get :accessing_local_assigns_in_inline_template, :local_name => "Local David" + get :accessing_local_assigns_in_inline_template, params: { local_name: "Local David" } assert_equal "Goodbye, Local David", @response.body assert_equal "text/html", @response.content_type end def test_should_implicitly_render_html_template_from_xhr_request - xhr :get, :render_implicit_html_template_from_xhr_request + get :render_implicit_html_template_from_xhr_request, xhr: true assert_equal "XHR!\nHello HTML!", @response.body end def test_should_implicitly_render_js_template_without_layout - xhr :get, :render_implicit_js_template_without_layout, :format => :js + get :render_implicit_js_template_without_layout, format: :js, xhr: true assert_no_match %r{<html>}, @response.body end @@ -1027,8 +1031,8 @@ class RenderTest < ActionController::TestCase def test_render_to_string_doesnt_break_assigns get :render_to_string_with_assigns - assert_equal "i'm before the render", assigns(:before) - assert_equal "i'm after the render", assigns(:after) + assert_equal "i'm before the render", @controller.instance_variable_get(:@before) + assert_equal "i'm after the render", @controller.instance_variable_get(:@after) end def test_bad_render_to_string_still_throws_exception @@ -1037,12 +1041,12 @@ class RenderTest < ActionController::TestCase def test_render_to_string_that_throws_caught_exception_doesnt_break_assigns assert_nothing_raised { get :render_to_string_with_caught_exception } - assert_equal "i'm before the render", assigns(:before) - assert_equal "i'm after the render", assigns(:after) + assert_equal "i'm before the render", @controller.instance_variable_get(:@before) + assert_equal "i'm after the render", @controller.instance_variable_get(:@after) end def test_accessing_params_in_template_with_layout - get :accessing_params_in_template_with_layout, :name => "David" + get :accessing_params_in_template_with_layout, params: { name: "David" } assert_equal "<html>Hello: David</html>", @response.body end @@ -1099,7 +1103,12 @@ class RenderTest < ActionController::TestCase # :addressed: def test_render_text_with_assigns get :render_text_with_assigns - assert_equal "world", assigns["hello"] + assert_equal "world", @controller.instance_variable_get(:@hello) + end + + def test_render_text_with_assigns_option + get :render_with_assigns_option + assert_equal 'world', response.body end # :ported: @@ -1160,22 +1169,22 @@ class RenderTest < ActionController::TestCase def test_render_to_string_partial get :render_to_string_with_partial - assert_equal "only partial", assigns(:partial_only) - assert_equal "Hello: david", assigns(:partial_with_locals) + assert_equal "only partial", @controller.instance_variable_get(:@partial_only) + assert_equal "Hello: david", @controller.instance_variable_get(:@partial_with_locals) assert_equal "text/html", @response.content_type end def test_render_to_string_with_template_and_html_partial get :render_to_string_with_template_and_html_partial - assert_equal "**only partial**\n", assigns(:text) - assert_equal "<strong>only partial</strong>\n", assigns(:html) + assert_equal "**only partial**\n", @controller.instance_variable_get(:@text) + assert_equal "<strong>only partial</strong>\n", @controller.instance_variable_get(:@html) assert_equal "<strong>only html partial</strong>\n", @response.body assert_equal "text/html", @response.content_type end def test_render_to_string_and_render_with_different_formats get :render_to_string_and_render_with_different_formats - assert_equal "<strong>only partial</strong>\n", assigns(:html) + assert_equal "<strong>only partial</strong>\n", @controller.instance_variable_get(:@html) assert_equal "**only partial**\n", @response.body assert_equal "text/plain", @response.content_type end @@ -1199,21 +1208,18 @@ class RenderTest < ActionController::TestCase def test_partial_with_form_builder get :partial_with_form_builder - assert_match(/<label/, @response.body) - assert_template('test/_form') + assert_equal "<label for=\"post_title\">Title</label>\n", @response.body end def test_partial_with_form_builder_subclass get :partial_with_form_builder_subclass - assert_match(/<label/, @response.body) - assert_template('test/_labelling_form') + assert_equal "<label for=\"post_title\">Title</label>\n", @response.body end def test_nested_partial_with_form_builder @controller = Fun::GamesController.new get :nested_partial_with_form_builder - assert_match(/<label/, @response.body) - assert_template('fun/games/_form') + assert_equal "<label for=\"post_title\">Title</label>\n", @response.body end def test_namespaced_object_partial @@ -1257,48 +1263,29 @@ class RenderTest < ActionController::TestCase assert_equal "Bonjour: davidBonjour: mary", @response.body end - def test_locals_option_to_assert_template_is_not_supported - get :partial_collection_with_locals - - warning_buffer = StringIO.new - $stderr = warning_buffer - - assert_template partial: 'customer_greeting', locals: { greeting: 'Bonjour' } - assert_equal "the :locals option to #assert_template is only supported in a ActionView::TestCase\n", warning_buffer.string - ensure - $stderr = STDERR - end - def test_partial_collection_with_spacer get :partial_collection_with_spacer assert_equal "Hello: davidonly partialHello: mary", @response.body - assert_template :partial => '_customer' end def test_partial_collection_with_spacer_which_uses_render get :partial_collection_with_spacer_which_uses_render assert_equal "Hello: davidpartial html\npartial with partial\nHello: mary", @response.body - assert_template :partial => '_customer' end def test_partial_collection_shorthand_with_locals get :partial_collection_shorthand_with_locals assert_equal "Bonjour: davidBonjour: mary", @response.body - assert_template :partial => 'customers/_customer', :count => 2 - assert_template :partial => '_completely_fake_and_made_up_template_that_cannot_possibly_be_rendered', :count => 0 end def test_partial_collection_shorthand_with_different_types_of_records get :partial_collection_shorthand_with_different_types_of_records assert_equal "Bonjour bad customer: mark0Bonjour good customer: craig1Bonjour bad customer: john2Bonjour good customer: zach3Bonjour good customer: brandon4Bonjour bad customer: dan5", @response.body - assert_template :partial => 'good_customers/_good_customer', :count => 3 - assert_template :partial => 'bad_customers/_bad_customer', :count => 3 end def test_empty_partial_collection get :empty_partial_collection assert_equal " ", @response.body - assert_template :partial => false end def test_partial_with_hash_object diff --git a/actionview/test/actionpack/controller/view_paths_test.rb b/actionview/test/actionpack/controller/view_paths_test.rb index c6e7a523b9..e99659c802 100644 --- a/actionview/test/actionpack/controller/view_paths_test.rb +++ b/actionview/test/actionpack/controller/view_paths_test.rb @@ -23,8 +23,8 @@ class ViewLoadPathsTest < ActionController::TestCase end def setup - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new + @request = ActionController::TestRequest.create + @response = ActionDispatch::TestResponse.new @controller = TestController.new @paths = TestController.view_paths end @@ -39,7 +39,7 @@ class ViewLoadPathsTest < ActionController::TestCase 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 } + assert_equal expand(paths), controller.view_paths.map(&:to_s) end def test_template_load_path_was_set_correctly diff --git a/actionview/test/active_record_unit.rb b/actionview/test/active_record_unit.rb index cca55c9af4..f9e94413b5 100644 --- a/actionview/test/active_record_unit.rb +++ b/actionview/test/active_record_unit.rb @@ -76,7 +76,7 @@ class ActiveRecordTestCase < ActionController::TestCase # Set our fixture path if ActiveRecordTestConnector.able_to_connect self.fixture_path = [FIXTURE_LOAD_PATH] - self.use_transactional_fixtures = false + self.use_transactional_tests = false end def self.fixtures(*args) diff --git a/actionview/test/activerecord/controller_runtime_test.rb b/actionview/test/activerecord/controller_runtime_test.rb index 469adff39a..af91348d76 100644 --- a/actionview/test/activerecord/controller_runtime_test.rb +++ b/actionview/test/activerecord/controller_runtime_test.rb @@ -4,7 +4,7 @@ require 'fixtures/project' require 'active_support/log_subscriber/test_helper' require 'action_controller/log_subscriber' -ActionController::Base.send :include, ActiveRecord::Railties::ControllerRuntime +ActionController::Base.include(ActiveRecord::Railties::ControllerRuntime) class ControllerRuntimeLogSubscriberTest < ActionController::TestCase class LogSubscriberController < ActionController::Base diff --git a/actionview/test/template/debug_helper_test.rb b/actionview/test/activerecord/debug_helper_test.rb index 5609694cd5..03cb1d5a91 100644 --- a/actionview/test/template/debug_helper_test.rb +++ b/actionview/test/activerecord/debug_helper_test.rb @@ -1,8 +1,14 @@ require 'active_record_unit' +require 'nokogiri' class DebugHelperTest < ActionView::TestCase def test_debug company = Company.new(name: "firebase") assert_match "name: firebase", debug(company) end + + def test_debug_with_marshal_error + obj = -> { } + assert_match obj.inspect, Nokogiri.XML(debug(obj)).content + end end diff --git a/actionview/test/activerecord/form_helper_activerecord_test.rb b/actionview/test/activerecord/form_helper_activerecord_test.rb index 0a62f49f35..2769b97445 100644 --- a/actionview/test/activerecord/form_helper_activerecord_test.rb +++ b/actionview/test/activerecord/form_helper_activerecord_test.rb @@ -35,10 +35,6 @@ class FormHelperActiveRecordTest < ActionView::TestCase end end - def _routes - Routes - end - include Routes.url_helpers def test_nested_fields_for_with_child_index_option_override_on_a_nested_attributes_collection_association diff --git a/actionview/test/activerecord/polymorphic_routes_test.rb b/actionview/test/activerecord/polymorphic_routes_test.rb index 5842b775bb..34b2698c7f 100644 --- a/actionview/test/activerecord/polymorphic_routes_test.rb +++ b/actionview/test/activerecord/polymorphic_routes_test.rb @@ -25,15 +25,17 @@ class Series < ActiveRecord::Base self.table_name = 'projects' end -class ModelDelegator < ActiveRecord::Base - self.table_name = 'projects' - +class ModelDelegator def to_model ModelDelegate.new end end class ModelDelegate + def persisted? + true + end + def model_name ActiveModel::Name.new(self.class) end @@ -111,7 +113,7 @@ class PolymorphicRoutesTest < ActionController::TestCase def test_passing_routes_proxy with_namespaced_routes(:blog) do - proxy = ActionDispatch::Routing::RoutesProxy.new(_routes, self) + proxy = ActionDispatch::Routing::RoutesProxy.new(_routes, self, _routes.url_helpers) @blog_post.save assert_url "http://example.com/posts/#{@blog_post.id}", [proxy, @blog_post] end @@ -206,7 +208,7 @@ class PolymorphicRoutesTest < ActionController::TestCase @series.save polymorphic_url([nil, @series]) end - assert_match(/undefined method `series_url' for/, exception.message) + assert_match(/undefined method `series_url'/, exception.message) end end @@ -605,13 +607,18 @@ class PolymorphicRoutesTest < ActionController::TestCase end end - def test_routing_a_to_model_delegate + def test_routing_to_a_model_delegate with_test_routes do - @delegator.save assert_url "http://example.com/model_delegates/overridden", @delegator end end + def test_nested_routing_to_a_model_delegate + with_test_routes do + assert_url "http://example.com/foo/model_delegates/overridden", [:foo, @delegator] + end + end + def with_namespaced_routes(name) with_routing do |set| set.draw do @@ -645,6 +652,9 @@ class PolymorphicRoutesTest < ActionController::TestCase end resources :series resources :model_delegates + namespace :foo do + resources :model_delegates + end end extend @routes.url_helpers diff --git a/actionview/test/activerecord/relation_cache_test.rb b/actionview/test/activerecord/relation_cache_test.rb new file mode 100644 index 0000000000..8e97417b94 --- /dev/null +++ b/actionview/test/activerecord/relation_cache_test.rb @@ -0,0 +1,18 @@ +require 'active_record_unit' + +class RelationCacheTest < ActionView::TestCase + tests ActionView::Helpers::CacheHelper + + def setup + @virtual_path = "path" + controller.cache_store = ActiveSupport::Cache::MemoryStore.new + end + + def test_cache_relation_other + cache(Project.all){ concat("Hello World") } + assert_equal "Hello World", controller.cache_store.read("views/projects-#{Project.count}/") + end + + def view_cache_dependencies; end + +end diff --git a/actionview/test/activerecord/render_partial_with_record_identification_test.rb b/actionview/test/activerecord/render_partial_with_record_identification_test.rb index 409370104d..9772ebb39e 100644 --- a/actionview/test/activerecord/render_partial_with_record_identification_test.rb +++ b/actionview/test/activerecord/render_partial_with_record_identification_test.rb @@ -52,43 +52,37 @@ class RenderPartialWithRecordIdentificationTest < ActiveRecordTestCase def test_rendering_partial_with_has_many_and_belongs_to_association get :render_with_has_many_and_belongs_to_association - assert_template 'projects/_project' - assert_equal assigns(:developer).projects.map(&:name).join, @response.body + assert_equal Developer.find(1).projects.map(&:name).join, @response.body end def test_rendering_partial_with_has_many_association get :render_with_has_many_association - assert_template 'replies/_reply' assert_equal 'Birdman is better!', @response.body end def test_rendering_partial_with_scope get :render_with_scope - assert_template 'replies/_reply' assert_equal 'Birdman is better!Nuh uh!', @response.body end def test_render_with_record get :render_with_record - assert_template 'developers/_developer' assert_equal 'David', @response.body end def test_render_with_record_collection get :render_with_record_collection - assert_template 'developers/_developer' assert_equal 'DavidJamisfixture_3fixture_4fixture_5fixture_6fixture_7fixture_8fixture_9fixture_10Jamis', @response.body end def test_render_with_record_collection_and_spacer_template get :render_with_record_collection_and_spacer_template - assert_equal assigns(:developer).projects.map(&:name).join('only partial'), @response.body + assert_equal Developer.find(1).projects.map(&:name).join('only partial'), @response.body end def test_rendering_partial_with_has_one_association mascot = Company.find(1).mascot get :render_with_has_one_association - assert_template 'mascots/_mascot' assert_equal mascot.name, @response.body end end @@ -130,13 +124,11 @@ class RenderPartialWithRecordIdentificationAndNestedControllersTest < ActiveReco def test_render_with_record_in_nested_controller get :render_with_record_in_nested_controller - assert_template %r{\Afun/games/_game\Z} assert_equal "Fun Pong\n", @response.body end def test_render_with_record_collection_in_nested_controller get :render_with_record_collection_in_nested_controller - assert_template %r{\Afun/games/_game\Z} assert_equal "Fun Pong\nFun Tank\n", @response.body end end @@ -149,7 +141,6 @@ class RenderPartialWithRecordIdentificationAndNestedControllersWithoutPrefixTest ActionView::Base.prefix_partial_path_with_controller_namespace = false get :render_with_record_in_nested_controller - assert_template %r{\Agames/_game\Z} assert_equal "Just Pong\n", @response.body ensure ActionView::Base.prefix_partial_path_with_controller_namespace = old_config @@ -160,7 +151,6 @@ class RenderPartialWithRecordIdentificationAndNestedControllersWithoutPrefixTest ActionView::Base.prefix_partial_path_with_controller_namespace = false get :render_with_record_collection_in_nested_controller - assert_template %r{\Agames/_game\Z} assert_equal "Just Pong\nJust Tank\n", @response.body ensure ActionView::Base.prefix_partial_path_with_controller_namespace = old_config @@ -172,13 +162,11 @@ class RenderPartialWithRecordIdentificationAndNestedDeeperControllersTest < Acti def test_render_with_record_in_deeper_nested_controller get :render_with_record_in_deeper_nested_controller - assert_template %r{\Afun/serious/games/_game\Z} assert_equal "Serious Chess\n", @response.body end def test_render_with_record_collection_in_deeper_nested_controller get :render_with_record_collection_in_deeper_nested_controller - assert_template %r{\Afun/serious/games/_game\Z} assert_equal "Serious Chess\nSerious Sudoku\nSerious Solitaire\n", @response.body end end @@ -191,7 +179,6 @@ class RenderPartialWithRecordIdentificationAndNestedDeeperControllersWithoutPref ActionView::Base.prefix_partial_path_with_controller_namespace = false get :render_with_record_in_deeper_nested_controller - assert_template %r{\Agames/_game\Z} assert_equal "Just Chess\n", @response.body ensure ActionView::Base.prefix_partial_path_with_controller_namespace = old_config @@ -202,7 +189,6 @@ class RenderPartialWithRecordIdentificationAndNestedDeeperControllersWithoutPref ActionView::Base.prefix_partial_path_with_controller_namespace = false get :render_with_record_collection_in_deeper_nested_controller - assert_template %r{\Agames/_game\Z} assert_equal "Just Chess\nJust Sudoku\nJust Solitaire\n", @response.body ensure ActionView::Base.prefix_partial_path_with_controller_namespace = old_config diff --git a/actionview/test/fixtures/actionpack/layout_tests/alt/layouts/alt.erb b/actionview/test/fixtures/actionpack/layout_tests/alt/layouts/alt.erb index e69de29bb2..60b81525b5 100644 --- a/actionview/test/fixtures/actionpack/layout_tests/alt/layouts/alt.erb +++ b/actionview/test/fixtures/actionpack/layout_tests/alt/layouts/alt.erb @@ -0,0 +1 @@ +alt.erb diff --git a/actionview/test/fixtures/actionpack/layouts/standard.text.erb b/actionview/test/fixtures/actionpack/layouts/standard.text.erb new file mode 100644 index 0000000000..a58afb1aa2 --- /dev/null +++ b/actionview/test/fixtures/actionpack/layouts/standard.text.erb @@ -0,0 +1 @@ +{{<%= yield %><%= @variable_for_layout %>}} diff --git a/actionview/test/fixtures/actionpack/test/hyphen-ated.erb b/actionview/test/fixtures/actionpack/test/hyphen-ated.erb index cd0875583a..28dbe94ee1 100644 --- a/actionview/test/fixtures/actionpack/test/hyphen-ated.erb +++ b/actionview/test/fixtures/actionpack/test/hyphen-ated.erb @@ -1 +1 @@ -Hello world! +hyphen-ated.erb
\ No newline at end of file diff --git a/actionview/test/fixtures/blog_public/.gitignore b/actionview/test/fixtures/blog_public/.gitignore deleted file mode 100644 index 312e635ee6..0000000000 --- a/actionview/test/fixtures/blog_public/.gitignore +++ /dev/null @@ -1 +0,0 @@ -absolute/* diff --git a/actionview/test/fixtures/blog_public/blog.html b/actionview/test/fixtures/blog_public/blog.html deleted file mode 100644 index 79ad44c010..0000000000 --- a/actionview/test/fixtures/blog_public/blog.html +++ /dev/null @@ -1 +0,0 @@ -/blog/blog.html
\ No newline at end of file diff --git a/actionview/test/fixtures/blog_public/index.html b/actionview/test/fixtures/blog_public/index.html deleted file mode 100644 index 2de3825481..0000000000 --- a/actionview/test/fixtures/blog_public/index.html +++ /dev/null @@ -1 +0,0 @@ -/blog/index.html
\ No newline at end of file diff --git a/actionview/test/fixtures/blog_public/subdir/index.html b/actionview/test/fixtures/blog_public/subdir/index.html deleted file mode 100644 index 517bded335..0000000000 --- a/actionview/test/fixtures/blog_public/subdir/index.html +++ /dev/null @@ -1 +0,0 @@ -/blog/subdir/index.html
\ No newline at end of file diff --git a/actionview/test/fixtures/digestor/events/_completed.html.erb b/actionview/test/fixtures/digestor/events/_completed.html.erb new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/actionview/test/fixtures/digestor/events/_completed.html.erb diff --git a/actionview/test/fixtures/digestor/events/index.html.erb b/actionview/test/fixtures/digestor/events/index.html.erb new file mode 100644 index 0000000000..bc45e41bcb --- /dev/null +++ b/actionview/test/fixtures/digestor/events/index.html.erb @@ -0,0 +1 @@ +<% # Template Dependency: events/* %>
\ No newline at end of file diff --git a/actionview/test/fixtures/functional_caching/fragment_cached_without_digest.html.erb b/actionview/test/fixtures/functional_caching/fragment_cached_without_digest.html.erb deleted file mode 100644 index 3125583a28..0000000000 --- a/actionview/test/fixtures/functional_caching/fragment_cached_without_digest.html.erb +++ /dev/null @@ -1,3 +0,0 @@ -<body> -<%= cache 'nodigest', skip_digest: true do %><p>ERB</p><% end %> -</body> diff --git a/actionview/test/fixtures/happy_path/render_action/hello_world.erb b/actionview/test/fixtures/happy_path/render_action/hello_world.erb deleted file mode 100644 index 6769dd60bd..0000000000 --- a/actionview/test/fixtures/happy_path/render_action/hello_world.erb +++ /dev/null @@ -1 +0,0 @@ -Hello world!
\ No newline at end of file diff --git a/actionview/test/fixtures/layouts/streaming_with_capture.erb b/actionview/test/fixtures/layouts/streaming_with_capture.erb new file mode 100644 index 0000000000..538c19ce3a --- /dev/null +++ b/actionview/test/fixtures/layouts/streaming_with_capture.erb @@ -0,0 +1,6 @@ +<%= yield :header -%> +<%= capture do %> + this works +<% end %> +<%= yield :footer -%> +<%= yield(:unknown).presence || "." -%> diff --git a/actionview/test/fixtures/multipart/bracketed_utf8_param b/actionview/test/fixtures/multipart/bracketed_utf8_param deleted file mode 100644 index df9cecea08..0000000000 --- a/actionview/test/fixtures/multipart/bracketed_utf8_param +++ /dev/null @@ -1,5 +0,0 @@ ---AaB03x -Content-Disposition: form-data; name="Iñtërnâtiônàlizætiøn_name[Iñtërnâtiônàlizætiøn_nested_name]" - -Iñtërnâtiônàlizætiøn_value ---AaB03x-- diff --git a/actionview/test/fixtures/multipart/single_utf8_param b/actionview/test/fixtures/multipart/single_utf8_param deleted file mode 100644 index 1d9fae7b17..0000000000 --- a/actionview/test/fixtures/multipart/single_utf8_param +++ /dev/null @@ -1,5 +0,0 @@ ---AaB03x -Content-Disposition: form-data; name="Iñtërnâtiônàlizætiøn_name" - -Iñtërnâtiônàlizætiøn_value ---AaB03x-- diff --git a/actionview/test/fixtures/project.rb b/actionview/test/fixtures/project.rb index c124a9e605..404b12cbab 100644 --- a/actionview/test/fixtures/project.rb +++ b/actionview/test/fixtures/project.rb @@ -1,3 +1,7 @@ class Project < ActiveRecord::Base has_and_belongs_to_many :developers, -> { uniq } + + def self.collection_cache_key(collection = all, timestamp_column = :updated_at) + "projects-#{collection.count}" + end end diff --git a/actionview/test/fixtures/scope/test/modgreet.erb b/actionview/test/fixtures/scope/test/modgreet.erb deleted file mode 100644 index 8947726e89..0000000000 --- a/actionview/test/fixtures/scope/test/modgreet.erb +++ /dev/null @@ -1 +0,0 @@ -<p>Beautiful modules!</p>
\ No newline at end of file diff --git a/actionview/test/fixtures/test/_FooBar.html.erb b/actionview/test/fixtures/test/_FooBar.html.erb new file mode 100644 index 0000000000..4bbe59410a --- /dev/null +++ b/actionview/test/fixtures/test/_FooBar.html.erb @@ -0,0 +1 @@ +🍣 diff --git a/actionview/test/fixtures/test/_a-in.html.erb b/actionview/test/fixtures/test/_a-in.html.erb new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/actionview/test/fixtures/test/_a-in.html.erb diff --git a/actionview/test/fixtures/test/_cached_customer.erb b/actionview/test/fixtures/test/_cached_customer.erb new file mode 100644 index 0000000000..52f35a3497 --- /dev/null +++ b/actionview/test/fixtures/test/_cached_customer.erb @@ -0,0 +1,3 @@ +<% cache cached_customer do %> + Hello: <%= cached_customer.name %> +<% end %>
\ No newline at end of file diff --git a/actionview/test/fixtures/test/_cached_customer_as.erb b/actionview/test/fixtures/test/_cached_customer_as.erb new file mode 100644 index 0000000000..fca8d19e34 --- /dev/null +++ b/actionview/test/fixtures/test/_cached_customer_as.erb @@ -0,0 +1,3 @@ +<% cache buyer do %> + <%= greeting %>: <%= customer.name %> +<% end %>
\ No newline at end of file diff --git a/actionview/test/fixtures/test/_label_with_block.erb b/actionview/test/fixtures/test/_label_with_block.erb index 40117e594e..94089ea93d 100644 --- a/actionview/test/fixtures/test/_label_with_block.erb +++ b/actionview/test/fixtures/test/_label_with_block.erb @@ -1,4 +1,4 @@ -<%= label 'post', 'message' do %> +<%= label('post', 'message')do %> Message <%= text_field 'post', 'message' %> <% end %> diff --git a/actionview/test/fixtures/test/_partial_name_in_local_assigns.erb b/actionview/test/fixtures/test/_partial_name_in_local_assigns.erb new file mode 100644 index 0000000000..28ee9f41c5 --- /dev/null +++ b/actionview/test/fixtures/test/_partial_name_in_local_assigns.erb @@ -0,0 +1 @@ +<%= local_assigns.has_key?(:partial_name_in_local_assigns) %>
\ No newline at end of file diff --git a/actionview/test/fixtures/test/_partial_shortcut_with_block_content.html.erb b/actionview/test/fixtures/test/_partial_shortcut_with_block_content.html.erb new file mode 100644 index 0000000000..352128f3ba --- /dev/null +++ b/actionview/test/fixtures/test/_partial_shortcut_with_block_content.html.erb @@ -0,0 +1,3 @@ +<%= render "test/layout_for_block_with_args" do |arg_1, arg_2| %> + Yielded: <%= arg_1 %>/<%= arg_2 %> +<% end %> diff --git a/actionview/test/lib/controller/fake_models.rb b/actionview/test/lib/controller/fake_models.rb index a463a08bb6..65c68fc34a 100644 --- a/actionview/test/lib/controller/fake_models.rb +++ b/actionview/test/lib/controller/fake_models.rb @@ -54,6 +54,22 @@ class Post < Struct.new(:title, :author_name, :body, :secret, :persisted, :writt def tags_attributes=(attributes); end end +class PostDelegator < Post + def to_model + PostDelegate.new + end +end + +class PostDelegate < Post + def self.human_attribute_name(attribute) + "Delegate #{super}" + end + + def model_name + ActiveModel::Name.new(self.class) + end +end + class Comment extend ActiveModel::Naming include ActiveModel::Conversion @@ -111,19 +127,6 @@ class CommentRelevance end end -class Sheep - extend ActiveModel::Naming - include ActiveModel::Conversion - - attr_reader :id - def to_key; id ? [id] : nil end - def save; @id = 1 end - def new_record?; @id.nil? end - def name - @id.nil? ? 'new sheep' : "sheep ##{@id}" - end -end - class TagRelevance extend ActiveModel::Naming include ActiveModel::Conversion @@ -183,3 +186,15 @@ end class Car < Struct.new(:color) end + +class Plane + attr_reader :to_key + + def model_name + OpenStruct.new param_key: 'airplane' + end + + def save + @to_key = [1] + end +end diff --git a/actionview/test/template/asset_tag_helper_test.rb b/actionview/test/template/asset_tag_helper_test.rb index dac1c7024d..496b33b35e 100644 --- a/actionview/test/template/asset_tag_helper_test.rb +++ b/actionview/test/template/asset_tag_helper_test.rb @@ -1,4 +1,3 @@ -require 'zlib' require 'abstract_unit' require 'active_support/ordered_options' @@ -180,6 +179,7 @@ class AssetTagHelperTest < ActionView::TestCase %(image_tag("xml.png")) => %(<img alt="Xml" src="/images/xml.png" />), %(image_tag("rss.gif", :alt => "rss syndication")) => %(<img alt="rss syndication" src="/images/rss.gif" />), %(image_tag("gold.png", :size => "20")) => %(<img alt="Gold" height="20" src="/images/gold.png" width="20" />), + %(image_tag("gold.png", :size => 20)) => %(<img alt="Gold" height="20" src="/images/gold.png" width="20" />), %(image_tag("gold.png", :size => "45x70")) => %(<img alt="Gold" height="70" src="/images/gold.png" width="45" />), %(image_tag("gold.png", "size" => "45x70")) => %(<img alt="Gold" height="70" src="/images/gold.png" width="45" />), %(image_tag("error.png", "size" => "45 x 70")) => %(<img alt="Error" src="/images/error.png" />), @@ -238,6 +238,7 @@ class AssetTagHelperTest < ActionView::TestCase %(video_tag("gold.m4v", "size" => "320x240")) => %(<video height="240" src="/videos/gold.m4v" width="320"></video>), %(video_tag("trailer.ogg", :poster => "screenshot.png")) => %(<video poster="/images/screenshot.png" src="/videos/trailer.ogg"></video>), %(video_tag("error.avi", "size" => "100")) => %(<video height="100" src="/videos/error.avi" width="100"></video>), + %(video_tag("error.avi", "size" => 100)) => %(<video height="100" src="/videos/error.avi" width="100"></video>), %(video_tag("error.avi", "size" => "100 x 100")) => %(<video src="/videos/error.avi"></video>), %(video_tag("error.avi", "size" => "x")) => %(<video src="/videos/error.avi"></video>), %(video_tag("http://media.rubyonrails.org/video/rails_blog_2.mov")) => %(<video src="http://media.rubyonrails.org/video/rails_blog_2.mov"></video>), @@ -309,6 +310,11 @@ class AssetTagHelperTest < ActionView::TestCase AssetPathToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) } end + def test_asset_path_tag_raises_an_error_for_nil_source + e = assert_raise(ArgumentError) { asset_path(nil) } + assert_equal("nil is not a valid asset source", e.message) + end + def test_asset_path_tag_to_not_create_duplicate_slashes @controller.config.asset_host = "host/" assert_dom_equal('http://host/foo', asset_path("foo")) @@ -463,6 +469,14 @@ class AssetTagHelperTest < ActionView::TestCase assert_equal({:size => '16x10'}, options) end + def test_image_tag_raises_an_error_for_competing_size_arguments + exception = assert_raise(ArgumentError) do + image_tag("gold.png", :height => "100", :width => "200", :size => "45x70") + end + + assert_equal("Cannot pass a :size option with a :height or :width option", exception.message) + end + def test_favicon_link_tag FaviconLinkToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) } end @@ -574,11 +588,13 @@ class AssetTagHelperTest < ActionView::TestCase end end - @controller.request.stubs(:ssl?).returns(false) - assert_equal "http://assets15.example.com/images/xml.png", image_path("xml.png") + @controller.request.stub(:ssl?, false) do + assert_equal "http://assets15.example.com/images/xml.png", image_path("xml.png") + end - @controller.request.stubs(:ssl?).returns(true) - assert_equal "http://localhost/images/xml.png", image_path("xml.png") + @controller.request.stub(:ssl?, true) do + assert_equal "http://localhost/images/xml.png", image_path("xml.png") + end end end diff --git a/actionview/test/template/atom_feed_helper_test.rb b/actionview/test/template/atom_feed_helper_test.rb index 68b44c4f0d..591cd71404 100644 --- a/actionview/test/template/atom_feed_helper_test.rb +++ b/actionview/test/template/atom_feed_helper_test.rb @@ -14,7 +14,7 @@ class ScrollsController < ActionController::Base FEEDS["defaults"] = <<-EOT atom_feed(:schema_date => '2008') do |feed| feed.title("My great blog!") - feed.updated((@scrolls.first.created_at)) + feed.updated(@scrolls.first.created_at) @scrolls.each do |scroll| feed.entry(scroll) do |entry| @@ -31,7 +31,7 @@ class ScrollsController < ActionController::Base FEEDS["entry_options"] = <<-EOT atom_feed do |feed| feed.title("My great blog!") - feed.updated((@scrolls.first.created_at)) + feed.updated(@scrolls.first.created_at) @scrolls.each do |scroll| feed.entry(scroll, :url => "/otherstuff/" + scroll.to_param.to_s, :updated => Time.utc(2007, 1, scroll.id)) do |entry| @@ -48,7 +48,7 @@ class ScrollsController < ActionController::Base FEEDS["entry_type_options"] = <<-EOT atom_feed(:schema_date => '2008') do |feed| feed.title("My great blog!") - feed.updated((@scrolls.first.created_at)) + feed.updated(@scrolls.first.created_at) @scrolls.each do |scroll| feed.entry(scroll, :type => 'text/xml') do |entry| @@ -62,10 +62,27 @@ class ScrollsController < ActionController::Base end end EOT + FEEDS["entry_url_false_option"] = <<-EOT + atom_feed do |feed| + feed.title("My great blog!") + feed.updated(@scrolls.first.created_at) + + @scrolls.each do |scroll| + feed.entry(scroll, :url => false) do |entry| + entry.title(scroll.title) + entry.content(scroll.body, :type => 'html') + + entry.author do |author| + author.name("DHH") + end + end + end + end + EOT FEEDS["xml_block"] = <<-EOT atom_feed do |feed| feed.title("My great blog!") - feed.updated((@scrolls.first.created_at)) + feed.updated(@scrolls.first.created_at) feed.author do |author| author.name("DHH") @@ -83,7 +100,7 @@ class ScrollsController < ActionController::Base atom_feed({'xmlns:app' => 'http://www.w3.org/2007/app', 'xmlns:openSearch' => 'http://a9.com/-/spec/opensearch/1.1/'}) do |feed| feed.title("My great blog!") - feed.updated((@scrolls.first.created_at)) + feed.updated(@scrolls.first.created_at) @scrolls.each do |scroll| feed.entry(scroll) do |entry| @@ -101,7 +118,7 @@ class ScrollsController < ActionController::Base FEEDS["feed_with_overridden_ids"] = <<-EOT atom_feed({:id => 'tag:test.rubyonrails.org,2008:test/'}) do |feed| feed.title("My great blog!") - feed.updated((@scrolls.first.created_at)) + feed.updated(@scrolls.first.created_at) @scrolls.each do |scroll| feed.entry(scroll, :id => "tag:test.rubyonrails.org,2008:"+scroll.id.to_s) do |entry| @@ -120,7 +137,7 @@ class ScrollsController < ActionController::Base atom_feed(:schema_date => '2008', :instruct => {'xml-stylesheet' => { :href=> 't.css', :type => 'text/css' }}) do |feed| feed.title("My great blog!") - feed.updated((@scrolls.first.created_at)) + feed.updated(@scrolls.first.created_at) @scrolls.each do |scroll| feed.entry(scroll) do |entry| @@ -138,7 +155,7 @@ class ScrollsController < ActionController::Base atom_feed(:schema_date => '2008', :instruct => {'target1' => [{ :a => '1', :b => '2' }, { :c => '3', :d => '4' }]}) do |feed| feed.title("My great blog!") - feed.updated((@scrolls.first.created_at)) + feed.updated(@scrolls.first.created_at) @scrolls.each do |scroll| feed.entry(scroll) do |entry| @@ -155,7 +172,7 @@ class ScrollsController < ActionController::Base FEEDS["feed_with_xhtml_content"] = <<-'EOT' atom_feed do |feed| feed.title("My great blog!") - feed.updated((@scrolls.first.created_at)) + feed.updated(@scrolls.first.created_at) @scrolls.each do |scroll| feed.entry(scroll) do |entry| @@ -180,7 +197,7 @@ class ScrollsController < ActionController::Base new_xml = Builder::XmlMarkup.new(:target=>'') atom_feed(:xml => new_xml) do |feed| feed.title("My great blog!") - feed.updated((@scrolls.first.created_at)) + feed.updated(@scrolls.first.created_at) @scrolls.each do |scroll| feed.entry(scroll) do |entry| @@ -214,28 +231,28 @@ class AtomFeedTest < ActionController::TestCase def test_feed_should_use_default_language_if_none_is_given with_restful_routing(:scrolls) do - get :index, :id => "defaults" + get :index, params: { id: "defaults" } assert_match(%r{xml:lang="en-US"}, @response.body) end end def test_feed_should_include_two_entries with_restful_routing(:scrolls) do - get :index, :id => "defaults" + get :index, params: { id: "defaults" } assert_select "entry", 2 end end def test_entry_should_only_use_published_if_created_at_is_present with_restful_routing(:scrolls) do - get :index, :id => "defaults" + get :index, params: { id: "defaults" } assert_select "published", 1 end end def test_providing_builder_to_atom_feed with_restful_routing(:scrolls) do - get :index, :id=>"provide_builder" + get :index, params: { id: "provide_builder" } # because we pass in the non-default builder, the content generated by the # helper should go 'nowhere'. Leaving the response body blank. assert @response.body.blank? @@ -244,7 +261,7 @@ class AtomFeedTest < ActionController::TestCase def test_entry_with_prefilled_options_should_use_those_instead_of_querying_the_record with_restful_routing(:scrolls) do - get :index, :id => "entry_options" + get :index, params: { id: "entry_options" } assert_select "updated", Time.utc(2007, 1, 1).xmlschema assert_select "updated", Time.utc(2007, 1, 2).xmlschema @@ -253,21 +270,21 @@ class AtomFeedTest < ActionController::TestCase def test_self_url_should_default_to_current_request_url with_restful_routing(:scrolls) do - get :index, :id => "defaults" + get :index, params: { id: "defaults" } assert_select "link[rel=self][href=\"http://www.nextangle.com/scrolls?id=defaults\"]" end end def test_feed_id_should_be_a_valid_tag with_restful_routing(:scrolls) do - get :index, :id => "defaults" + get :index, params: { id: "defaults" } assert_select "id", :text => "tag:www.nextangle.com,2008:/scrolls?id=defaults" end end def test_entry_id_should_be_a_valid_tag with_restful_routing(:scrolls) do - get :index, :id => "defaults" + get :index, params: { id: "defaults" } assert_select "entry id", :text => "tag:www.nextangle.com,2008:Scroll/1" assert_select "entry id", :text => "tag:www.nextangle.com,2008:Scroll/2" end @@ -275,14 +292,14 @@ class AtomFeedTest < ActionController::TestCase def test_feed_should_allow_nested_xml_blocks with_restful_routing(:scrolls) do - get :index, :id => "xml_block" + get :index, params: { id: "xml_block" } assert_select "author name", :text => "DHH" end end def test_feed_should_include_atomPub_namespace with_restful_routing(:scrolls) do - get :index, :id => "feed_with_atomPub_namespace" + get :index, params: { id: "feed_with_atomPub_namespace" } assert_match %r{xml:lang="en-US"}, @response.body assert_match %r{xmlns="http://www.w3.org/2005/Atom"}, @response.body assert_match %r{xmlns:app="http://www.w3.org/2007/app"}, @response.body @@ -291,7 +308,7 @@ class AtomFeedTest < ActionController::TestCase def test_feed_should_allow_overriding_ids with_restful_routing(:scrolls) do - get :index, :id => "feed_with_overridden_ids" + get :index, params: { id: "feed_with_overridden_ids" } assert_select "id", :text => "tag:test.rubyonrails.org,2008:test/" assert_select "entry id", :text => "tag:test.rubyonrails.org,2008:1" assert_select "entry id", :text => "tag:test.rubyonrails.org,2008:2" @@ -300,7 +317,7 @@ class AtomFeedTest < ActionController::TestCase def test_feed_xml_processing_instructions with_restful_routing(:scrolls) do - get :index, :id => 'feed_with_xml_processing_instructions' + get :index, params: { id: 'feed_with_xml_processing_instructions' } assert_match %r{<\?xml-stylesheet [^\?]*type="text/css"}, @response.body assert_match %r{<\?xml-stylesheet [^\?]*href="t.css"}, @response.body end @@ -308,7 +325,7 @@ class AtomFeedTest < ActionController::TestCase def test_feed_xml_processing_instructions_duplicate_targets with_restful_routing(:scrolls) do - get :index, :id => 'feed_with_xml_processing_instructions_duplicate_targets' + get :index, params: { id: 'feed_with_xml_processing_instructions_duplicate_targets' } assert_match %r{<\?target1 (a="1" b="2"|b="2" a="1")\?>}, @response.body assert_match %r{<\?target1 (c="3" d="4"|d="4" c="3")\?>}, @response.body end @@ -316,7 +333,7 @@ class AtomFeedTest < ActionController::TestCase def test_feed_xhtml with_restful_routing(:scrolls) do - get :index, :id => "feed_with_xhtml_content" + get :index, params: { id: "feed_with_xhtml_content" } assert_match %r{xmlns="http://www.w3.org/1999/xhtml"}, @response.body assert_select "summary", :text => /Something Boring/ assert_select "summary", :text => /after 2/ @@ -325,18 +342,25 @@ class AtomFeedTest < ActionController::TestCase def test_feed_entry_type_option_default_to_text_html with_restful_routing(:scrolls) do - get :index, :id => 'defaults' + get :index, params: { id: 'defaults' } assert_select "entry link[rel=alternate][type=\"text/html\"]" end end def test_feed_entry_type_option_specified with_restful_routing(:scrolls) do - get :index, :id => 'entry_type_options' + get :index, params: { id: 'entry_type_options' } assert_select "entry link[rel=alternate][type=\"text/xml\"]" end end + def test_feed_entry_url_false_option_adds_no_link + with_restful_routing(:scrolls) do + get :index, params: { id: 'entry_url_false_option' } + assert_select "entry link", false + end + end + private def with_restful_routing(resources) with_routing do |set| diff --git a/actionview/test/template/capture_helper_test.rb b/actionview/test/template/capture_helper_test.rb index f213da5934..1e099d482c 100644 --- a/actionview/test/template/capture_helper_test.rb +++ b/actionview/test/template/capture_helper_test.rb @@ -210,10 +210,4 @@ class CaptureHelperTest < ActionView::TestCase def alt_encoding(output_buffer) output_buffer.encoding == Encoding::US_ASCII ? Encoding::UTF_8 : Encoding::US_ASCII end - - def view_with_controller - TestController.new.view_context.tap do |view| - view.output_buffer = ActionView::OutputBuffer.new - end - end end diff --git a/actionview/test/template/controller_helper_test.rb b/actionview/test/template/controller_helper_test.rb new file mode 100644 index 0000000000..b5e94ea4f1 --- /dev/null +++ b/actionview/test/template/controller_helper_test.rb @@ -0,0 +1,21 @@ +require 'abstract_unit' + +class ControllerHelperTest < ActionView::TestCase + tests ActionView::Helpers::ControllerHelper + + class SpecializedFormBuilder < ActionView::Helpers::FormBuilder ; end + + def test_assign_controller_sets_default_form_builder + @controller = OpenStruct.new(default_form_builder: SpecializedFormBuilder) + assign_controller(@controller) + + assert_equal SpecializedFormBuilder, self.default_form_builder + end + + def test_assign_controller_skips_default_form_builder + @controller = OpenStruct.new + assign_controller(@controller) + + assert_nil self.default_form_builder + end +end diff --git a/actionview/test/template/date_helper_test.rb b/actionview/test/template/date_helper_test.rb index 0cdb130710..9212420ec9 100644 --- a/actionview/test/template/date_helper_test.rb +++ b/actionview/test/template/date_helper_test.rb @@ -130,7 +130,7 @@ class DateHelperTest < ActionView::TestCase def test_distance_in_words_with_mathn_required # test we avoid Integer#/ (redefined by mathn) - require 'mathn' + silence_warnings { require "mathn" } from = Time.utc(2004, 6, 6, 21, 45, 0) assert_distance_of_time_in_words(from) end @@ -1504,7 +1504,7 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="">Choose seconds</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18" selected="selected">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n<option value="32">32</option>\n<option value="33">33</option>\n<option value="34">34</option>\n<option value="35">35</option>\n<option value="36">36</option>\n<option value="37">37</option>\n<option value="38">38</option>\n<option value="39">39</option>\n<option value="40">40</option>\n<option value="41">41</option>\n<option value="42">42</option>\n<option value="43">43</option>\n<option value="44">44</option>\n<option value="45">45</option>\n<option value="46">46</option>\n<option value="47">47</option>\n<option value="48">48</option>\n<option value="49">49</option>\n<option value="50">50</option>\n<option value="51">51</option>\n<option value="52">52</option>\n<option value="53">53</option>\n<option value="54">54</option>\n<option value="55">55</option>\n<option value="56">56</option>\n<option value="57">57</option>\n<option value="58">58</option>\n<option value="59">59</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), :prompt => true, :include_seconds => true, + assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), :include_seconds => true, :prompt => {:hour => 'Choose hour', :minute => 'Choose minute', :second => 'Choose seconds'}) end @@ -2330,7 +2330,7 @@ class DateHelperTest < ActionView::TestCase # The love zone is UTC+0 mytz = Class.new(ActiveSupport::TimeZone) { attr_accessor :now - }.create('tenderlove', 0) + }.create('tenderlove', 0, ActiveSupport::TimeZone.find_tzinfo('UTC')) now = Time.mktime(2004, 6, 15, 16, 35, 0) mytz.now = now @@ -3217,12 +3217,4 @@ class DateHelperTest < ActionView::TestCase expected = '<time datetime="2013-02-20T00:00:00+00:00">20 Feb 00:00</time>' assert_equal expected, time_tag(time, :format => :short) end - - protected - def with_env_tz(new_tz = 'US/Eastern') - old_tz, ENV['TZ'] = ENV['TZ'], new_tz - yield - ensure - old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ') - end end diff --git a/actionview/test/template/dependency_tracker_test.rb b/actionview/test/template/dependency_tracker_test.rb index bb375076c6..672b4747ec 100644 --- a/actionview/test/template/dependency_tracker_test.rb +++ b/actionview/test/template/dependency_tracker_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 require 'abstract_unit' require 'action_view/dependency_tracker' @@ -61,7 +60,6 @@ class ERBTrackerTest < Minitest::Test end def test_dependency_of_template_partial_with_layout - skip # FIXME: Needs to be fixed properly, right now we can only match one dependency per line. Need multiple! template = FakeTemplate.new("<%# render partial: 'messages/show', layout: 'messages/layout' %>", :erb) tracker = make_tracker("multiple/_dependencies", template) diff --git a/actionview/test/template/digestor_test.rb b/actionview/test/template/digestor_test.rb index c2b8439df3..dde757b5a2 100644 --- a/actionview/test/template/digestor_test.rb +++ b/actionview/test/template/digestor_test.rb @@ -1,5 +1,6 @@ require 'abstract_unit' require 'fileutils' +require 'action_view/dependency_tracker' class FixtureTemplate attr_reader :source, :handler @@ -15,12 +16,13 @@ end class FixtureFinder FIXTURES_DIR = "#{File.dirname(__FILE__)}/../fixtures/digestor" - attr_reader :details + attr_reader :details, :view_paths attr_accessor :formats attr_accessor :variants def initialize @details = {} + @view_paths = ActionView::PathSet.new(['digestor']) @formats = [] @variants = [] end @@ -75,6 +77,34 @@ class TemplateDigestorTest < ActionView::TestCase end end + def test_explicit_dependency_wildcard + assert_digest_difference("events/index") do + change_template("events/_completed") + end + end + + def test_explicit_dependency_wildcard_picks_up_added_file + old_caching, ActionView::Resolver.caching = ActionView::Resolver.caching, false + + assert_digest_difference("events/index") do + add_template("events/_uncompleted") + end + ensure + remove_template("events/_uncompleted") + ActionView::Resolver.caching = old_caching + end + + def test_explicit_dependency_wildcard_picks_up_removed_file + old_caching, ActionView::Resolver.caching = ActionView::Resolver.caching, false + add_template("events/_subscribers_changed") + + assert_digest_difference("events/index") do + remove_template("events/_subscribers_changed") + end + ensure + ActionView::Resolver.caching = old_caching + end + def test_second_level_dependency assert_digest_difference("messages/show") do change_template("comments/_comments") @@ -111,6 +141,18 @@ class TemplateDigestorTest < ActionView::TestCase end end + def test_logging_of_missing_template_for_dependencies + assert_logged "'messages/something_missing' file doesn't exist, so no dependencies" do + dependencies("messages/something_missing") + end + end + + def test_logging_of_missing_template_for_nested_dependencies + assert_logged "'messages/something_missing' file doesn't exist, so no dependencies" do + nested_dependencies("messages/something_missing") + end + end + def test_nested_template_directory assert_digest_difference("messages/show") do change_template("messages/actions/_move") @@ -207,7 +249,7 @@ class TemplateDigestorTest < ActionView::TestCase end def test_variants - assert_digest_difference("messages/new", false, variants: [:iphone]) do + assert_digest_difference("messages/new", variants: [:iphone]) do change_template("messages/new", :iphone) change_template("messages/_header", :iphone) end @@ -227,16 +269,6 @@ class TemplateDigestorTest < ActionView::TestCase assert_not_equal digest_phone, digest_fridge_phone end - def test_cache_template_loading - resolver_before = ActionView::Resolver.caching - ActionView::Resolver.caching = false - assert_digest_difference("messages/edit", true) do - change_template("comments/_comment") - end - ensure - ActionView::Resolver.caching = resolver_before - end - def test_digest_cache_cleanup_with_recursion first_digest = digest("level/_recursion") second_digest = digest("level/_recursion") @@ -279,9 +311,9 @@ class TemplateDigestorTest < ActionView::TestCase end end - def assert_digest_difference(template_name, persistent = false, options = {}) + def assert_digest_difference(template_name, options = {}) previous_digest = digest(template_name, options) - ActionView::Digestor.cache.clear unless persistent + ActionView::Digestor.cache.clear yield @@ -298,6 +330,14 @@ class TemplateDigestorTest < ActionView::TestCase ActionView::Digestor.digest({ name: template_name, finder: finder }.merge(options)) end + def dependencies(template_name) + ActionView::Digestor.new({ name: template_name, finder: finder }).dependencies + end + + def nested_dependencies(template_name) + ActionView::Digestor.new({ name: template_name, finder: finder }).nested_dependencies + end + def finder @finder ||= FixtureFinder.new end @@ -309,4 +349,9 @@ class TemplateDigestorTest < ActionView::TestCase f.write "\nTHIS WAS CHANGED!" end end + alias_method :add_template, :change_template + + def remove_template(template_name) + File.delete("digestor/#{template_name}.html.erb") + end end diff --git a/actionview/test/template/erb_util_test.rb b/actionview/test/template/erb_util_test.rb index 3bb84cbc50..3e72be31de 100644 --- a/actionview/test/template/erb_util_test.rb +++ b/actionview/test/template/erb_util_test.rb @@ -84,7 +84,7 @@ class ErbUtilTest < ActiveSupport::TestCase end def test_rest_in_ascii - (0..127).to_a.map {|int| int.chr }.each do |chr| + (0..127).to_a.map(&:chr).each do |chr| next if %('"&<>).include?(chr) assert_equal chr, html_escape(chr) end diff --git a/actionview/test/template/form_helper_test.rb b/actionview/test/template/form_helper_test.rb index f2238d1443..aef137935a 100644 --- a/actionview/test/template/form_helper_test.rb +++ b/actionview/test/template/form_helper_test.rb @@ -40,6 +40,9 @@ class FormHelperTest < ActionView::TestCase }, tag: { value: "Tag" + }, + post_delegate: { + title: 'Delegate model_name title' } } } @@ -81,6 +84,9 @@ class FormHelperTest < ActionView::TestCase body: "Write body here" } }, + post_delegate: { + title: 'Delegate model_name title' + }, tag: { value: "Tag" } @@ -99,7 +105,9 @@ class FormHelperTest < ActionView::TestCase }.new end def @post.to_key; [123]; end - def @post.id_before_type_cast; 123; end + def @post.id; 0; end + def @post.id_before_type_cast; "omg"; end + def @post.id_came_from_user?; true; end def @post.to_param; '123'; end @post.persisted = true @@ -115,6 +123,10 @@ class FormHelperTest < ActionView::TestCase @post.tags = [] @post.tags << Tag.new + @post_delegator = PostDelegator.new + + @post_delegator.title = 'Hello World' + @car = Car.new("#000FFF") end @@ -247,6 +259,18 @@ class FormHelperTest < ActionView::TestCase end end + def test_label_with_non_active_record_object + form_for(OpenStruct.new(name:'ok'), as: 'person', url: 'an_url', html: { id: 'create-person' }) do |f| + f.label(:name) + end + + expected = whole_form("an_url", "create-person", "new_person", method: "post") do + '<label for="person_name">Name</label>' + end + + assert_dom_equal expected, output_buffer + end + def test_label_with_for_attribute_as_symbol assert_dom_equal('<label for="my_for">Title</label>', label(:post, :title, nil, for: "my_for")) end @@ -335,6 +359,22 @@ class FormHelperTest < ActionView::TestCase ) end + def test_label_with_to_model + assert_dom_equal( + %{<label for="post_delegator_title">Delegate Title</label>}, + label(:post_delegator, :title) + ) + end + + def test_label_with_to_model_and_overriden_model_name + with_locale :label do + assert_dom_equal( + %{<label for="post_delegator_title">Delegate model_name title</label>}, + label(:post_delegator, :title) + ) + end + end + def test_text_field_placeholder_without_locales with_locale :placeholder do assert_dom_equal('<input id="post_body" name="post[body]" placeholder="Body" type="text" value="Back to the hill and over it again!" />', text_field(:post, :body, placeholder: true)) @@ -347,12 +387,28 @@ class FormHelperTest < ActionView::TestCase end end + def test_text_field_placeholder_with_locales_and_to_model + with_locale :placeholder do + assert_dom_equal( + '<input id="post_delegator_title" name="post_delegator[title]" placeholder="Delegate model_name title" type="text" value="Hello World" />', + text_field(:post_delegator, :title, placeholder: true) + ) + end + end + def test_text_field_placeholder_with_human_attribute_name with_locale :placeholder do assert_dom_equal('<input id="post_cost" name="post[cost]" placeholder="Total cost" type="text" />', text_field(:post, :cost, placeholder: true)) end end + def test_text_field_placeholder_with_human_attribute_name_and_to_model + assert_dom_equal( + '<input id="post_delegator_title" name="post_delegator[title]" placeholder="Delegate Title" type="text" value="Hello World" />', + text_field(:post_delegator, :title, placeholder: true) + ) + end + def test_text_field_placeholder_with_string_value with_locale :placeholder do assert_dom_equal('<input id="post_cost" name="post[cost]" placeholder="HOW MUCH?" type="text" />', text_field(:post, :cost, placeholder: "HOW MUCH?")) @@ -472,18 +528,33 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal expected, text_field(object_name, "title") end - def test_file_field_has_no_size + def test_file_field_does_generate_a_hidden_field + expected = '<input name="user[avatar]" type="hidden" value="" /><input id="user_avatar" name="user[avatar]" type="file" />' + assert_dom_equal expected, file_field("user", "avatar") + end + + def test_file_field_does_not_generate_a_hidden_field_if_included_hidden_option_is_false expected = '<input id="user_avatar" name="user[avatar]" type="file" />' + assert_dom_equal expected, file_field("user", "avatar", include_hidden: false) + end + + def test_file_field_does_not_generate_a_hidden_field_if_included_hidden_option_is_false_with_key_as_string + expected = '<input id="user_avatar" name="user[avatar]" type="file" />' + assert_dom_equal expected, file_field("user", "avatar", "include_hidden" => false) + end + + def test_file_field_has_no_size + expected = '<input name="user[avatar]" type="hidden" value="" /><input id="user_avatar" name="user[avatar]" type="file" />' assert_dom_equal expected, file_field("user", "avatar") end def test_file_field_with_multiple_behavior - expected = '<input id="import_file" multiple="multiple" name="import[file][]" type="file" />' + expected = '<input name="import[file][]" type="hidden" value="" /><input id="import_file" multiple="multiple" name="import[file][]" type="file" />' assert_dom_equal expected, file_field("import", "file", :multiple => true) end def test_file_field_with_multiple_behavior_and_explicit_name - expected = '<input id="import_file" multiple="multiple" name="custom" type="file" />' + expected = '<input name="custom" type="hidden" value="" /><input id="import_file" multiple="multiple" name="custom" type="file" />' assert_dom_equal expected, file_field("import", "file", :multiple => true, :name => "custom") end @@ -885,9 +956,29 @@ class FormHelperTest < ActionView::TestCase ) end - def test_text_area_with_value_before_type_cast + def test_inputs_use_before_type_cast_to_retain_information_from_validations_like_numericality + assert_dom_equal( + %{<textarea id="post_id" name="post[id]">\nomg</textarea>}, + text_area("post", "id") + ) + end + + def test_inputs_dont_use_before_type_cast_when_value_did_not_come_from_user + class << @post + undef id_came_from_user? + def id_came_from_user?; false; end + end + + assert_dom_equal( + %{<textarea id="post_id" name="post[id]">\n0</textarea>}, + text_area("post", "id") + ) + end + + def test_inputs_use_before_typecast_when_object_doesnt_respond_to_came_from_user + class << @post; undef id_came_from_user?; end assert_dom_equal( - %{<textarea id="post_id" name="post[id]">\n123</textarea>}, + %{<textarea id="post_id" name="post[id]">\nomg</textarea>}, text_area("post", "id") ) end @@ -928,6 +1019,11 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal(expected, search_field("contact", "notes_query")) end + def test_search_field_with_onsearch_value + expected = %{<input onsearch="true" type="search" name="contact[notes_query]" id="contact_notes_query" incremental="true" />} + assert_dom_equal(expected, search_field("contact", "notes_query", onsearch: true)) + end + def test_telephone_field expected = %{<input id="user_cell" name="user[cell]" type="tel" />} assert_dom_equal(expected, telephone_field("user", "cell")) @@ -1481,7 +1577,7 @@ class FormHelperTest < ActionView::TestCase "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" + "<input name='post[secret]' type='hidden' value='0' />" + "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" + - "<input name='commit' type='submit' value='Create post' />" + + "<input name='commit' data-disable-with='Create post' type='submit' value='Create post' />" + "<button name='button' type='submit'>Create post</button>" + "<button name='button' type='submit'><span>Create post</span></button>" end @@ -1714,7 +1810,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form("/posts/123", "create-post", "edit_post", method: "patch", multipart: true) do - "<input name='post[file]' type='file' id='post_file' />" + "<input name='post[file]' type='hidden' value='' /><input name='post[file]' type='file' id='post_file' />" end assert_dom_equal expected, output_buffer @@ -1730,7 +1826,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch", multipart: true) do - "<input name='post[comment][file]' type='file' id='post_comment_file' />" + "<input name='post[comment][file]' type='hidden' value='' /><input name='post[comment][file]' type='file' id='post_comment_file' />" end assert_dom_equal expected, output_buffer @@ -1758,7 +1854,7 @@ class FormHelperTest < ActionView::TestCase expected = whole_form("/posts/44", "edit_post_44", "edit_post", method: "patch") do "<input name='post[title]' type='text' id='post_title' value='And his name will be forty and four.' />" + - "<input name='commit' type='submit' value='Edit post' />" + "<input name='commit' data-disable-with='Edit post' type='submit' value='Edit post' />" end assert_dom_equal expected, output_buffer @@ -1779,12 +1875,26 @@ class FormHelperTest < ActionView::TestCase "<textarea name='other_name[body]' id='other_name_body'>\nBack to the hill and over it again!</textarea>" + "<input name='other_name[secret]' value='0' type='hidden' />" + "<input name='other_name[secret]' checked='checked' id='other_name_secret' value='1' type='checkbox' />" + - "<input name='commit' value='Create post' type='submit' />" + "<input name='commit' value='Create post' data-disable-with='Create post' type='submit' />" end assert_dom_equal expected, output_buffer end + def test_form_tags_do_not_call_private_properties_on_form_object + obj = Class.new do + private + + def private_property + raise "This method should not be called." + end + end.new + + form_for(obj, as: "other_name", url: '/', html: { id: "edit-other-name" }) do |f| + assert_raise(NoMethodError) { f.hidden_field(:private_property) } + end + end + def test_form_for_with_method_as_part_of_html_options form_for(@post, url: '/', html: { id: 'create-post', method: :delete }) do |f| concat f.text_field(:title) @@ -1850,6 +1960,30 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal expected, output_buffer end + def test_form_for_enforce_utf8_true + form_for(:post, enforce_utf8: true) do |f| + concat f.text_field(:title) + end + + expected = whole_form("/", nil, nil, enforce_utf8: true) do + "<input name='post[title]' type='text' id='post_title' value='Hello World' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_for_enforce_utf8_false + form_for(:post, enforce_utf8: false) do |f| + concat f.text_field(:title) + end + + expected = whole_form("/", nil, nil, enforce_utf8: false) do + "<input name='post[title]' type='text' id='post_title' value='Hello World' />" + end + + assert_dom_equal expected, output_buffer + end + def test_form_for_with_remote_in_html form_for(@post, url: '/', html: { remote: true, id: 'create-post', method: :patch }) do |f| concat f.text_field(:title) @@ -1869,21 +2003,22 @@ class FormHelperTest < ActionView::TestCase def test_form_for_with_remote_without_html @post.persisted = false - @post.stubs(:to_key).returns(nil) - form_for(@post, remote: true) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end + @post.stub(:to_key, nil) do + form_for(@post, remote: true) do |f| + concat f.text_field(:title) + concat f.text_area(:body) + concat f.check_box(:secret) + end - expected = whole_form("/posts", "new_post", "new_post", remote: true) do - "<input name='post[title]' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" + - "<input name='post[secret]' type='hidden' value='0' />" + - "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" - end + expected = whole_form("/posts", "new_post", "new_post", remote: true) do + "<input name='post[title]' type='text' id='post_title' value='Hello World' />" + + "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" + + "<input name='post[secret]' type='hidden' value='0' />" + + "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" + end - assert_dom_equal expected, output_buffer + assert_dom_equal expected, output_buffer + end end def test_form_for_without_object @@ -1949,7 +2084,7 @@ class FormHelperTest < ActionView::TestCase expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do "<div class='field_with_errors'><label for='post_author_name' class='label'>Author name</label></div>" + "<div class='field_with_errors'><input name='post[author_name]' type='text' id='post_author_name' value='' /></div>" + - "<input name='commit' type='submit' value='Create post' />" + "<input name='commit' data-disable-with='Create post' type='submit' value='Create post' />" end assert_dom_equal expected, output_buffer @@ -1967,7 +2102,7 @@ class FormHelperTest < ActionView::TestCase expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do "<div class='field_with_errors'><label for='post_author_name' class='label'>Author name</label></div>" + "<div class='field_with_errors'><input name='post[author_name]' type='text' id='post_author_name' value='' /></div>" + - "<input name='commit' type='submit' value='Create post' />" + "<input name='commit' data-disable-with='Create post' type='submit' value='Create post' />" end assert_dom_equal expected, output_buffer @@ -2086,16 +2221,17 @@ class FormHelperTest < ActionView::TestCase def test_submit_with_object_as_new_record_and_locale_strings with_locale :submit do @post.persisted = false - @post.stubs(:to_key).returns(nil) - form_for(@post) do |f| - concat f.submit - end + @post.stub(:to_key, nil) do + form_for(@post) do |f| + concat f.submit + end - expected = whole_form('/posts', 'new_post', 'new_post') do - "<input name='commit' type='submit' value='Create Post' />" - end + expected = whole_form('/posts', 'new_post', 'new_post') do + "<input name='commit' data-disable-with='Create Post' type='submit' value='Create Post' />" + end - assert_dom_equal expected, output_buffer + assert_dom_equal expected, output_buffer + end end end @@ -2106,7 +2242,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - "<input name='commit' type='submit' value='Confirm Post changes' />" + "<input name='commit' data-disable-with='Confirm Post changes' type='submit' value='Confirm Post changes' />" end assert_dom_equal expected, output_buffer @@ -2120,7 +2256,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form do - "<input name='commit' class='extra' type='submit' value='Save changes' />" + "<input name='commit' class='extra' data-disable-with='Save changes' type='submit' value='Save changes' />" end assert_dom_equal expected, output_buffer @@ -2134,7 +2270,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form('/posts/123', 'edit_another_post', 'edit_another_post', method: 'patch') do - "<input name='commit' type='submit' value='Update your Post' />" + "<input name='commit' data-disable-with='Update your Post' type='submit' value='Update your Post' />" end assert_dom_equal expected, output_buffer @@ -2673,11 +2809,12 @@ class FormHelperTest < ActionView::TestCase def test_nested_fields_label_translation_with_more_than_10_records @post.comments = Array.new(11) { |id| Comment.new(id + 1) } - I18n.expects(:t).with('post.comments.body', default: [:"comment.body", ''], scope: "helpers.label").times(11).returns "Write body here" - - form_for(@post) do |f| - f.fields_for(:comments) do |cf| - concat cf.label(:body) + params = 11.times.map { ['post.comments.body', default: [:"comment.body", ''], scope: "helpers.label"] } + assert_called_with(I18n, :t, params, returns: "Write body here") do + form_for(@post) do |f| + f.fields_for(:comments) do |cf| + concat cf.label(:body) + end end end end @@ -2744,6 +2881,23 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal expected, output_buffer end + def test_nested_fields_for_with_child_index_as_lambda_option_override_on_a_nested_attributes_collection_association + @post.comments = [] + + form_for(@post) do |f| + concat f.fields_for(:comments, Comment.new(321), child_index: -> { 'abc' } ) { |cf| + concat cf.text_field(:name) + } + end + + expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do + '<input id="post_comments_attributes_abc_name" name="post[comments_attributes][abc][name]" type="text" value="comment #321" />' + + '<input id="post_comments_attributes_abc_id" name="post[comments_attributes][abc][id]" type="hidden" value="321" />' + end + + assert_dom_equal expected, output_buffer + end + class FakeAssociationProxy def to_ary [1, 2, 3] @@ -3118,6 +3272,30 @@ class FormHelperTest < ActionView::TestCase ActionView::Base.default_form_builder = old_default_form_builder end + def test_form_builder_override + self.default_form_builder = LabelledFormBuilder + + output_buffer = fields_for(:post, @post) do |f| + concat f.text_field(:title) + end + + expected = "<label for='title'>Title:</label> <input name='post[title]' type='text' id='post_title' value='Hello World' /><br/>" + + assert_dom_equal expected, output_buffer + end + + def test_lazy_loading_form_builder_override + self.default_form_builder = "FormHelperTest::LabelledFormBuilder" + + output_buffer = fields_for(:post, @post) do |f| + concat f.text_field(:title) + end + + expected = "<label for='title'>Title:</label> <input name='post[title]' type='text' id='post_title' value='Hello World' /><br/>" + + assert_dom_equal expected, output_buffer + end + def test_fields_for_with_labelled_builder output_buffer = fields_for(:post, @post, builder: LabelledFormBuilder) do |f| concat f.text_field(:title) @@ -3299,8 +3477,14 @@ class FormHelperTest < ActionView::TestCase protected - def hidden_fields(method = nil) - txt = %{<input name="utf8" type="hidden" value="✓" />} + def hidden_fields(options = {}) + method = options[:method] + + if options.fetch(:enforce_utf8, true) + txt = %{<input name="utf8" type="hidden" value="✓" />} + else + txt = '' + end if method && !%w(get post).include?(method.to_s) txt << %{<input name="_method" type="hidden" value="#{method}" />} @@ -3324,7 +3508,7 @@ class FormHelperTest < ActionView::TestCase method, remote, multipart = options.values_at(:method, :remote, :multipart) - form_text(action, id, html_class, remote, multipart, method) + hidden_fields(method) + contents + "</form>" + form_text(action, id, html_class, remote, multipart, method) + hidden_fields(options.slice :method, :enforce_utf8) + contents + "</form>" end def protect_against_forgery? diff --git a/actionview/test/template/form_options_helper_i18n_test.rb b/actionview/test/template/form_options_helper_i18n_test.rb index 4972ea6511..26ede09a5f 100644 --- a/actionview/test/template/form_options_helper_i18n_test.rb +++ b/actionview/test/template/form_options_helper_i18n_test.rb @@ -14,8 +14,9 @@ class FormOptionsHelperI18nTests < ActionView::TestCase end def test_select_with_prompt_true_translates_prompt_message - I18n.expects(:translate).with('helpers.select.prompt', { :default => 'Please select' }) - select('post', 'category', [], :prompt => true) + assert_called_with(I18n, :translate, ['helpers.select.prompt', { :default => 'Please select' }]) do + select('post', 'category', [], :prompt => true) + end end def test_select_with_translated_prompt diff --git a/actionview/test/template/form_options_helper_test.rb b/actionview/test/template/form_options_helper_test.rb index d25fa3706f..d7daba8bf3 100644 --- a/actionview/test/template/form_options_helper_test.rb +++ b/actionview/test/template/form_options_helper_test.rb @@ -645,6 +645,13 @@ class FormOptionsHelperTest < ActionView::TestCase ) end + def test_select_with_include_blank_false_and_required + @post = Post.new + @post.category = "<mus>" + e = assert_raises(ArgumentError) { select("post", "category", %w( abe <mus> hest), { include_blank: false }, required: 'required') } + assert_match(/include_blank cannot be false for a required field./, e.message) + end + def test_select_with_blank_as_string @post = Post.new @post.category = "<mus>" diff --git a/actionview/test/template/form_tag_helper_test.rb b/actionview/test/template/form_tag_helper_test.rb index 2d89332841..a9d9562580 100644 --- a/actionview/test/template/form_tag_helper_test.rb +++ b/actionview/test/template/form_tag_helper_test.rb @@ -210,13 +210,13 @@ class FormTagHelperTest < ActionView::TestCase end def test_select_tag_with_multiple - actual = select_tag "colors", "<option>Red</option><option>Blue</option><option>Green</option>".html_safe, :multiple => :true - expected = %(<select id="colors" multiple="multiple" name="colors"><option>Red</option><option>Blue</option><option>Green</option></select>) + actual = select_tag "colors", "<option>Red</option><option>Blue</option><option>Green</option>".html_safe, multiple: true + expected = %(<select id="colors" multiple="multiple" name="colors[]"><option>Red</option><option>Blue</option><option>Green</option></select>) assert_dom_equal expected, actual end def test_select_tag_disabled - actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, :disabled => :true + actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, disabled: true expected = %(<select id="places" disabled="disabled" name="places"><option>Home</option><option>Work</option><option>Pub</option></select>) assert_dom_equal expected, actual end @@ -232,6 +232,18 @@ class FormTagHelperTest < ActionView::TestCase assert_dom_equal expected, actual end + def test_select_tag_with_include_blank_false + actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, include_blank: false + expected = %(<select id="places" name="places"><option>Home</option><option>Work</option><option>Pub</option></select>) + assert_dom_equal expected, actual + end + + def test_select_tag_with_include_blank_string + actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, include_blank: 'Choose' + expected = %(<select id="places" name="places"><option value="">Choose</option><option>Home</option><option>Work</option><option>Pub</option></select>) + assert_dom_equal expected, actual + end + def test_select_tag_with_prompt actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, :prompt => "string" expected = %(<select id="places" name="places"><option value="">string</option><option>Home</option><option>Work</option><option>Pub</option></select>) @@ -340,7 +352,7 @@ class FormTagHelperTest < ActionView::TestCase end def test_text_field_disabled - actual = text_field_tag "title", "Hello!", :disabled => :true + actual = text_field_tag "title", "Hello!", disabled: true expected = %(<input id="title" name="title" disabled="disabled" type="text" value="Hello!" />) assert_dom_equal expected, actual end @@ -421,6 +433,44 @@ class FormTagHelperTest < ActionView::TestCase ) end + def test_empty_submit_tag + assert_dom_equal( + %(<input data-disable-with="Save" name='commit' type="submit" value="Save" />), + submit_tag("Save") + ) + end + + def test_empty_submit_tag_with_opt_out + ActionView::Base.automatically_disable_submit_tag = false + assert_dom_equal( + %(<input name='commit' type="submit" value="Save" />), + submit_tag("Save") + ) + ensure + ActionView::Base.automatically_disable_submit_tag = true + end + + def test_data_disable_with_string + assert_dom_equal( + %(<input data-disable-with="Processing..." data-confirm="Are you sure?" name='commit' type="submit" value="Save" />), + submit_tag("Save", { "data-disable-with" => "Processing...", "data-confirm" => "Are you sure?" }) + ) + end + + def test_data_disable_with_boolean + assert_dom_equal( + %(<input data-confirm="Are you sure?" name='commit' type="submit" value="Save" />), + submit_tag("Save", { "data-disable-with" => false, "data-confirm" => "Are you sure?" }) + ) + end + + def test_data_hash_disable_with_boolean + assert_dom_equal( + %(<input data-confirm="Are you sure?" name='commit' type="submit" value="Save" />), + submit_tag("Save", { :data => { :confirm => "Are you sure?", :disable_with => false } }) + ) + end + def test_submit_tag_with_no_onclick_options assert_dom_equal( %(<input name='commit' data-disable-with="Saving..." type="submit" value="Save" />), @@ -430,7 +480,7 @@ class FormTagHelperTest < ActionView::TestCase def test_submit_tag_with_confirmation assert_dom_equal( - %(<input name='commit' type='submit' value='Save' data-confirm="Are you sure?" />), + %(<input name='commit' type='submit' value='Save' data-confirm="Are you sure?" data-disable-with="Save" />), submit_tag("Save", :data => { :confirm => "Are you sure?" }) ) end @@ -498,6 +548,13 @@ class FormTagHelperTest < ActionView::TestCase ) end + def test_button_tag_with_data_disable_with_option + assert_dom_equal( + %(<button name="button" type="submit" data-disable-with="Please wait...">Checkout</button>), + button_tag("Checkout", data: { disable_with: "Please wait..." }) + ) + end + def test_image_submit_tag_with_confirmation assert_dom_equal( %(<input alt="Save" type="image" src="/images/save.gif" data-confirm="Are you sure?" />), diff --git a/actionview/test/template/javascript_helper_test.rb b/actionview/test/template/javascript_helper_test.rb index 9ba7f64ad1..9f1535ef53 100644 --- a/actionview/test/template/javascript_helper_test.rb +++ b/actionview/test/template/javascript_helper_test.rb @@ -3,14 +3,7 @@ require 'abstract_unit' class JavaScriptHelperTest < ActionView::TestCase tests ActionView::Helpers::JavaScriptHelper - def _evaluate_assigns_and_ivars() end - - attr_accessor :formats, :output_buffer - - def update_details(details) - @details = details - yield if block_given? - end + attr_accessor :output_buffer setup do @old_escape_html_entities_in_json = ActiveSupport.escape_html_entities_in_json diff --git a/actionview/test/template/lookup_context_test.rb b/actionview/test/template/lookup_context_test.rb index 4f7823045e..14dafd7d63 100644 --- a/actionview/test/template/lookup_context_test.rb +++ b/actionview/test/template/lookup_context_test.rb @@ -108,10 +108,11 @@ class LookupContextTest < ActiveSupport::TestCase end test "found templates respects given formats if one cannot be found from template or handler" do - ActionView::Template::Handlers::Builder.expects(:default_format).returns(nil) - @lookup_context.formats = [:text] - template = @lookup_context.find("hello", %w(test)) - assert_equal [:text], template.formats + assert_called(ActionView::Template::Handlers::Builder, :default_format, returns: nil) do + @lookup_context.formats = [:text] + template = @lookup_context.find("hello", %w(test)) + assert_equal [:text], template.formats + end end test "adds fallbacks to view paths when required" do @@ -210,45 +211,50 @@ end class LookupContextWithFalseCaching < ActiveSupport::TestCase def setup @resolver = ActionView::FixtureResolver.new("test/_foo.erb" => ["Foo", Time.utc(2000)]) - ActionView::Resolver.stubs(:caching?).returns(false) @lookup_context = ActionView::LookupContext.new(@resolver, {}) end test "templates are always found in the resolver but timestamp is checked before being compiled" do - template = @lookup_context.find("foo", %w(test), true) - assert_equal "Foo", template.source - - # Now we are going to change the template, but it won't change the returned template - # since the timestamp is the same. - @resolver.hash["test/_foo.erb"][0] = "Bar" - template = @lookup_context.find("foo", %w(test), true) - assert_equal "Foo", template.source - - # Now update the timestamp. - @resolver.hash["test/_foo.erb"][1] = Time.now.utc - template = @lookup_context.find("foo", %w(test), true) - assert_equal "Bar", template.source + ActionView::Resolver.stub(:caching?, false) do + template = @lookup_context.find("foo", %w(test), true) + assert_equal "Foo", template.source + + # Now we are going to change the template, but it won't change the returned template + # since the timestamp is the same. + @resolver.hash["test/_foo.erb"][0] = "Bar" + template = @lookup_context.find("foo", %w(test), true) + assert_equal "Foo", template.source + + # Now update the timestamp. + @resolver.hash["test/_foo.erb"][1] = Time.now.utc + template = @lookup_context.find("foo", %w(test), true) + assert_equal "Bar", template.source + end end test "if no template was found in the second lookup, with no cache, raise error" do - template = @lookup_context.find("foo", %w(test), true) - assert_equal "Foo", template.source + ActionView::Resolver.stub(:caching?, false) do + template = @lookup_context.find("foo", %w(test), true) + assert_equal "Foo", template.source - @resolver.hash.clear - assert_raise ActionView::MissingTemplate do - @lookup_context.find("foo", %w(test), true) + @resolver.hash.clear + assert_raise ActionView::MissingTemplate do + @lookup_context.find("foo", %w(test), true) + end end end test "if no template was cached in the first lookup, retrieval should work in the second call" do - @resolver.hash.clear - assert_raise ActionView::MissingTemplate do - @lookup_context.find("foo", %w(test), true) - end + ActionView::Resolver.stub(:caching?, false) do + @resolver.hash.clear + assert_raise ActionView::MissingTemplate do + @lookup_context.find("foo", %w(test), true) + end - @resolver.hash["test/_foo.erb"] = ["Foo", Time.utc(2000)] - template = @lookup_context.find("foo", %w(test), true) - assert_equal "Foo", template.source + @resolver.hash["test/_foo.erb"] = ["Foo", Time.utc(2000)] + template = @lookup_context.find("foo", %w(test), true) + assert_equal "Foo", template.source + end end end diff --git a/actionview/test/template/number_helper_test.rb b/actionview/test/template/number_helper_test.rb index b59883b760..631d45586b 100644 --- a/actionview/test/template/number_helper_test.rb +++ b/actionview/test/template/number_helper_test.rb @@ -1,3 +1,4 @@ +# encoding: utf-8 require "abstract_unit" class NumberHelperTest < ActionView::TestCase @@ -21,6 +22,7 @@ class NumberHelperTest < ActionView::TestCase assert_equal "<b>1,234,567,890.50</b> $", number_to_currency("1234567890.50", format: "<b>%n</b> %u") assert_equal "<b>1,234,567,890.50</b> $", number_to_currency("-1234567890.50", negative_format: "<b>%n</b> %u") assert_equal "<b>1,234,567,890.50</b> $", number_to_currency("-1234567890.50", 'negative_format' => "<b>%n</b> %u") + assert_equal '₹ 12,30,000.00', number_to_currency(1230000, delimiter_pattern: /(\d+?)(?=(\d\d)+(\d)(?!\d))/, unit: '₹', format: "%u %n") end def test_number_to_percentage @@ -35,6 +37,10 @@ class NumberHelperTest < ActionView::TestCase assert_equal "98a%", number_to_percentage("98a") assert_equal "NaN%", number_to_percentage(Float::NAN) assert_equal "Inf%", number_to_percentage(Float::INFINITY) + assert_equal "NaN%", number_to_percentage(Float::NAN, precision: 0) + assert_equal "Inf%", number_to_percentage(Float::INFINITY, precision: 0) + assert_equal "NaN%", number_to_percentage(Float::NAN, precision: 1) + assert_equal "Inf%", number_to_percentage(Float::INFINITY, precision: 1) end def test_number_with_delimiter diff --git a/actionview/test/template/record_identifier_test.rb b/actionview/test/template/record_identifier_test.rb index 22038110a5..04898c0b0e 100644 --- a/actionview/test/template/record_identifier_test.rb +++ b/actionview/test/template/record_identifier_test.rb @@ -9,7 +9,6 @@ class RecordIdentifierTest < ActiveSupport::TestCase @record = @klass.new @singular = 'comment' @plural = 'comments' - @uncountable = Sheep end def test_dom_id_with_new_record @@ -47,3 +46,46 @@ class RecordIdentifierTest < ActiveSupport::TestCase assert_equal @singular, ActionView::RecordIdentifier.dom_class(@record) end end + +class RecordIdentifierWithoutActiveModelTest < ActiveSupport::TestCase + include ActionView::RecordIdentifier + + def setup + @record = Plane.new + end + + def test_dom_id_with_new_record + assert_equal "new_airplane", dom_id(@record) + end + + def test_dom_id_with_new_record_and_prefix + assert_equal "custom_prefix_airplane", dom_id(@record, :custom_prefix) + end + + def test_dom_id_with_saved_record + @record.save + assert_equal "airplane_1", dom_id(@record) + end + + def test_dom_id_with_prefix + @record.save + assert_equal "edit_airplane_1", dom_id(@record, :edit) + end + + def test_dom_class + assert_equal 'airplane', dom_class(@record) + end + + def test_dom_class_with_prefix + assert_equal "custom_prefix_airplane", dom_class(@record, :custom_prefix) + end + + def test_dom_id_as_singleton_method + @record.save + assert_equal "airplane_1", ActionView::RecordIdentifier.dom_id(@record) + end + + def test_dom_class_as_singleton_method + assert_equal 'airplane', ActionView::RecordIdentifier.dom_class(@record) + end +end diff --git a/actionview/test/template/record_tag_helper_test.rb b/actionview/test/template/record_tag_helper_test.rb index ab84bccb56..bfc5d04bed 100644 --- a/actionview/test/template/record_tag_helper_test.rb +++ b/actionview/test/template/record_tag_helper_test.rb @@ -2,7 +2,7 @@ require 'abstract_unit' class RecordTagPost extend ActiveModel::Naming - include ActiveModel::Conversion + attr_accessor :id, :body def initialize @@ -14,7 +14,6 @@ class RecordTagPost end class RecordTagHelperTest < ActionView::TestCase - include RenderERBUtils tests ActionView::Helpers::RecordTagHelper @@ -24,94 +23,10 @@ class RecordTagHelperTest < ActionView::TestCase end def test_content_tag_for - expected = %(<li class="record_tag_post" id="record_tag_post_45"></li>) - actual = content_tag_for(:li, @post) - assert_dom_equal expected, actual - end - - def test_content_tag_for_prefix - expected = %(<ul class="archived_record_tag_post" id="archived_record_tag_post_45"></ul>) - actual = content_tag_for(:ul, @post, :archived) - assert_dom_equal expected, actual - end - - def test_content_tag_for_with_extra_html_options - expected = %(<tr class="record_tag_post special" id="record_tag_post_45" style='background-color: #f0f0f0'></tr>) - actual = content_tag_for(:tr, @post, class: "special", style: "background-color: #f0f0f0") - assert_dom_equal expected, actual - end - - def test_content_tag_for_with_array_css_class - expected = %(<tr class="record_tag_post special odd" id="record_tag_post_45"></tr>) - actual = content_tag_for(:tr, @post, class: ["special", "odd"]) - assert_dom_equal expected, actual - end - - def test_content_tag_for_with_prefix_and_extra_html_options - expected = %(<tr class="archived_record_tag_post special" id="archived_record_tag_post_45" style='background-color: #f0f0f0'></tr>) - actual = content_tag_for(:tr, @post, :archived, class: "special", style: "background-color: #f0f0f0") - assert_dom_equal expected, actual - end - - def test_block_not_in_erb_multiple_calls - expected = %(<div class="record_tag_post special" id="record_tag_post_45">What a wonderful world!</div>) - actual = div_for(@post, class: "special") { @post.body } - assert_dom_equal expected, actual - actual = div_for(@post, class: "special") { @post.body } - assert_dom_equal expected, actual - end - - def test_block_works_with_content_tag_for_in_erb - expected = %(<tr class="record_tag_post" id="record_tag_post_45">What a wonderful world!</tr>) - actual = render_erb("<%= content_tag_for(:tr, @post) do %><%= @post.body %><% end %>") - assert_dom_equal expected, actual - end - - def test_div_for_in_erb - expected = %(<div class="record_tag_post special" id="record_tag_post_45">What a wonderful world!</div>) - actual = render_erb("<%= div_for(@post, class: 'special') do %><%= @post.body %><% end %>") - assert_dom_equal expected, actual - end - - def test_content_tag_for_collection - post_1 = RecordTagPost.new { |post| post.id = 101; post.body = "Hello!" } - post_2 = RecordTagPost.new { |post| post.id = 102; post.body = "World!" } - expected = %(<li class="record_tag_post" id="record_tag_post_101">Hello!</li>\n<li class="record_tag_post" id="record_tag_post_102">World!</li>) - actual = content_tag_for(:li, [post_1, post_2]) { |post| post.body } - assert_dom_equal expected, actual - end - - def test_content_tag_for_collection_without_given_block - post_1 = RecordTagPost.new.tap { |post| post.id = 101; post.body = "Hello!" } - post_2 = RecordTagPost.new.tap { |post| post.id = 102; post.body = "World!" } - expected = %(<li class="record_tag_post" id="record_tag_post_101"></li>\n<li class="record_tag_post" id="record_tag_post_102"></li>) - actual = content_tag_for(:li, [post_1, post_2]) - assert_dom_equal expected, actual - end - - def test_div_for_collection - post_1 = RecordTagPost.new { |post| post.id = 101; post.body = "Hello!" } - post_2 = RecordTagPost.new { |post| post.id = 102; post.body = "World!" } - expected = %(<div class="record_tag_post" id="record_tag_post_101">Hello!</div>\n<div class="record_tag_post" id="record_tag_post_102">World!</div>) - actual = div_for([post_1, post_2]) { |post| post.body } - assert_dom_equal expected, actual - end - - def test_content_tag_for_single_record_is_html_safe - result = div_for(@post, class: "special") { @post.body } - assert result.html_safe? - end - - def test_content_tag_for_collection_is_html_safe - post_1 = RecordTagPost.new { |post| post.id = 101; post.body = "Hello!" } - post_2 = RecordTagPost.new { |post| post.id = 102; post.body = "World!" } - result = content_tag_for(:li, [post_1, post_2]) { |post| post.body } - assert result.html_safe? + assert_raises(NoMethodError) { content_tag_for(:li, @post) } end - def test_content_tag_for_does_not_change_options_hash - options = { class: "important" } - content_tag_for(:li, @post, options) - assert_equal({ class: "important" }, options) + def test_div_for + assert_raises(NoMethodError) { div_for(@post, class: "special") } end end diff --git a/actionview/test/template/render_test.rb b/actionview/test/template/render_test.rb index 85817119ba..9c2c9507b7 100644 --- a/actionview/test/template/render_test.rb +++ b/actionview/test/template/render_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 require 'abstract_unit' require 'controller/fake_models' @@ -8,7 +7,10 @@ end module RenderTestCases def setup_view(paths) @assigns = { :secret => 'in the sauce' } - @view = ActionView::Base.new(paths, @assigns) + @view = Class.new(ActionView::Base) do + def view_cache_dependencies; end + end.new(paths, @assigns) + @controller_view = TestController.new.view_context # Reload and register danish language for testing @@ -16,7 +18,7 @@ module RenderTestCases I18n.backend.store_translations 'pt-BR', {} # Ensure original are still the same since we are reindexing view paths - assert_equal ORIGINAL_LOCALES, I18n.available_locales.map {|l| l.to_s }.sort + assert_equal ORIGINAL_LOCALES, I18n.available_locales.map(&:to_s).sort end def test_render_without_options @@ -62,9 +64,10 @@ module RenderTestCases def test_render_template_with_a_missing_partial_of_another_format @view.lookup_context.formats = [:html] - assert_raise ActionView::Template::Error, "Missing partial /_missing with {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder]}" do + e = assert_raise ActionView::Template::Error do @view.render(:template => "with_format", :formats => [:json]) end + assert_includes(e.message, "Missing partial /_missing with {:locale=>[:en], :formats=>[:json], :variants=>[], :handlers=>[:raw, :erb, :builder, :ruby]}.") end def test_render_file_with_locale @@ -172,18 +175,12 @@ module RenderTestCases assert_equal "only partial", @view.render("test/partial_only", :counter_counter => 5) end - def test_render_partial_with_invalid_name - e = assert_raises(ArgumentError) { @view.render(:partial => "test/200") } - assert_equal "The partial name (test/200) is not a valid Ruby identifier; " + - "make sure your partial name starts with a lowercase letter or underscore, " + - "and is followed by any combination of letters, numbers and underscores.", e.message + def test_render_partial_with_number + assert_nothing_raised { @view.render(:partial => "test/200") } end def test_render_partial_with_missing_filename - e = assert_raises(ArgumentError) { @view.render(:partial => "test/") } - assert_equal "The partial name (test/) is not a valid Ruby identifier; " + - "make sure your partial name starts with a lowercase letter or underscore, " + - "and is followed by any combination of letters, numbers and underscores.", e.message + assert_raises(ActionView::MissingTemplate) { @view.render(:partial => "test/") } end def test_render_partial_with_incompatible_object @@ -191,10 +188,25 @@ module RenderTestCases assert_equal "'#{nil.inspect}' is not an ActiveModel-compatible object. It must implement :to_partial_path.", e.message end + def test_render_partial_starting_with_a_capital + assert_nothing_raised { @view.render(:partial => 'test/FooBar') } + end + def test_render_partial_with_hyphen - e = assert_raises(ArgumentError) { @view.render(:partial => "test/a-in") } - assert_equal "The partial name (test/a-in) is not a valid Ruby identifier; " + - "make sure your partial name starts with a lowercase letter or underscore, " + + assert_nothing_raised { @view.render(:partial => "test/a-in") } + end + + def test_render_partial_with_invalid_option_as + e = assert_raises(ArgumentError) { @view.render(:partial => "test/partial_only", :as => 'a-in') } + assert_equal "The value (a-in) of the option `as` is not a valid Ruby identifier; " + + "make sure it starts with lowercase letter, " + + "and is followed by any combination of letters, numbers and underscores.", e.message + end + + def test_render_partial_with_hyphen_and_invalid_option_as + e = assert_raises(ArgumentError) { @view.render(:partial => "test/a-in", :as => 'a-in') } + assert_equal "The value (a-in) of the option `as` is not a valid Ruby identifier; " + + "make sure it starts with lowercase letter, " + "and is followed by any combination of letters, numbers and underscores.", e.message end @@ -268,6 +280,14 @@ module RenderTestCases assert_nil @view.render(:partial => "test/customer", :collection => nil) end + def test_render_partial_without_object_does_not_put_partial_name_to_local_assigns + assert_equal 'false', @view.render(partial: 'test/partial_name_in_local_assigns') + end + + def test_render_partial_with_nil_object_puts_partial_name_to_local_assigns + assert_equal 'true', @view.render(partial: 'test/partial_name_in_local_assigns', object: nil) + end + def test_render_partial_with_nil_values_in_collection assert_equal "Hello: davidHello: Anonymous", @view.render(:partial => "test/customer", :collection => [ Customer.new("david"), nil ]) end @@ -466,6 +486,11 @@ module RenderTestCases @view.render(:partial => 'test/partial_with_partial', :layout => 'test/layout_for_partial', :locals => { :name => 'Foo!'}) end + def test_render_partial_shortcut_with_block_content + assert_equal %(Before (shortcut test)\nBefore\n\n Yielded: arg1/arg2\n\nAfter\nAfter), + @view.render(partial: "test/partial_shortcut_with_block_content", layout: "test/layout_for_partial", locals: { name: "shortcut test" }) + end + def test_render_layout_with_a_nested_render_layout_call assert_equal %(Before (Foo!)\nBefore (Bar!)\npartial html\nAfter\npartial with layout\n\nAfter), @view.render(:partial => 'test/partial_with_layout', :layout => 'test/layout_for_partial', :locals => { :name => 'Foo!'}) @@ -584,3 +609,47 @@ class LazyViewRenderTest < ActiveSupport::TestCase silence_warnings { Encoding.default_external = old } end end + +class CachedCollectionViewRenderTest < CachedViewRenderTest + class CachedCustomer < Customer; end + + teardown do + ActionView::PartialRenderer.collection_cache.clear + end + + test "with custom key" do + customer = Customer.new("david") + key = cache_key([customer, 'key'], "test/_customer") + + ActionView::PartialRenderer.collection_cache.write(key, 'Hello') + + assert_equal "Hello", + @view.render(partial: "test/customer", collection: [customer], cache: ->(item) { [item, 'key'] }) + end + + test "automatic caching with inferred cache name" do + customer = CachedCustomer.new("david") + key = cache_key(customer, "test/_cached_customer") + + ActionView::PartialRenderer.collection_cache.write(key, 'Cached') + + assert_equal "Cached", + @view.render(partial: "test/cached_customer", collection: [customer]) + end + + test "automatic caching with as name" do + customer = CachedCustomer.new("david") + key = cache_key(customer, "test/_cached_customer_as") + + ActionView::PartialRenderer.collection_cache.write(key, 'Cached') + + assert_equal "Cached", + @view.render(partial: "test/cached_customer_as", collection: [customer], as: :buyer) + end + + private + def cache_key(names, virtual_path) + digest = ActionView::Digestor.digest name: virtual_path, finder: @view.lookup_context, dependencies: [] + @view.fragment_cache_key([ *Array(names), digest ]) + end +end diff --git a/actionview/test/template/sanitize_helper_test.rb b/actionview/test/template/sanitize_helper_test.rb index e4be21be2c..efe846a7eb 100644 --- a/actionview/test/template/sanitize_helper_test.rb +++ b/actionview/test/template/sanitize_helper_test.rb @@ -29,6 +29,10 @@ class SanitizeHelperTest < ActionView::TestCase assert_equal "", strip_tags("<script>") end + def test_strip_tags_will_not_encode_special_characters + assert_equal "test\r\n\r\ntest", strip_tags("test\r\n\r\ntest") + end + def test_sanitize_is_marked_safe assert sanitize("<html><script></script></html>").html_safe? end diff --git a/actionview/test/template/streaming_render_test.rb b/actionview/test/template/streaming_render_test.rb index 8a24d78e74..d06ba4ceb0 100644 --- a/actionview/test/template/streaming_render_test.rb +++ b/actionview/test/template/streaming_render_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 require 'abstract_unit' class TestController < ActionController::Base @@ -105,4 +104,8 @@ class FiberedTest < ActiveSupport::TestCase buffered_render(:template => "test/nested_streaming", :layout => "layouts/streaming") end + def test_render_with_streaming_and_capture + assert_equal "Yes, \n this works\n like a charm.", + buffered_render(template: "test/streaming", layout: "layouts/streaming_with_capture") + end end diff --git a/actionview/test/template/tag_helper_test.rb b/actionview/test/template/tag_helper_test.rb index ce89d5728e..d037447567 100644 --- a/actionview/test/template/tag_helper_test.rb +++ b/actionview/test/template/tag_helper_test.rb @@ -50,6 +50,11 @@ class TagHelperTest < ActionView::TestCase assert_dom_equal "<div>Hello world!</div>", buffer end + def test_content_tag_with_block_in_erb_containing_non_displayed_erb + buffer = render_erb("<%= content_tag(:p) do %><% 1 %><% end %>") + assert_dom_equal "<p></p>", buffer + end + def test_content_tag_with_block_and_options_in_erb buffer = render_erb("<%= content_tag(:div, :class => 'green') do %>Hello world!<% end %>") assert_dom_equal %(<div class="green">Hello world!</div>), buffer @@ -64,6 +69,11 @@ class TagHelperTest < ActionView::TestCase content_tag("a", "href" => "create") { "Create" } end + def test_content_tag_with_block_and_non_string_outside_out_of_erb + assert_equal content_tag("p"), + content_tag("p") { 3.times { "do_something" } } + end + def test_content_tag_nested_in_content_tag_out_of_erb assert_equal content_tag("p", content_tag("b", "Hello")), content_tag("p") { content_tag("b", "Hello") }, diff --git a/actionview/test/template/template_test.rb b/actionview/test/template/template_test.rb index c94508d678..921011b073 100644 --- a/actionview/test/template/template_test.rb +++ b/actionview/test/template/template_test.rb @@ -118,15 +118,17 @@ class TestERBTemplate < ActiveSupport::TestCase def test_refresh_with_templates @template = new_template("Hello", :virtual_path => "test/foo/bar") @template.locals = [:key] - @context.lookup_context.expects(:find_template).with("bar", %w(test/foo), false, [:key]).returns("template") - assert_equal "template", @template.refresh(@context) + assert_called_with(@context.lookup_context, :find_template,["bar", %w(test/foo), false, [:key]], returns: "template") do + assert_equal "template", @template.refresh(@context) + end end def test_refresh_with_partials @template = new_template("Hello", :virtual_path => "test/_foo") @template.locals = [:key] - @context.lookup_context.expects(:find_template).with("foo", %w(test), true, [:key]).returns("partial") - assert_equal "partial", @template.refresh(@context) + assert_called_with(@context.lookup_context, :find_template,[ "foo", %w(test), true, [:key]], returns: "partial") do + assert_equal "partial", @template.refresh(@context) + end end def test_refresh_raises_an_error_without_virtual_path @@ -183,10 +185,43 @@ class TestERBTemplate < ActiveSupport::TestCase end def test_error_when_template_isnt_valid_utf8 - assert_raises(ActionView::Template::Error, /\xFC/) do + e = assert_raises ActionView::Template::Error do @template = new_template("hello \xFCmlat", :virtual_path => nil) render end + assert_match(/\xFC/, e.message) + end + + def test_not_eligible_for_collection_caching_without_cache_call + [ + "<%= 'Hello' %>", + "<% cache_customer = 42 %>", + "<% cache customer.name do %><% end %>", + "<% my_cache customer do %><% end %>" + ].each do |body| + template = new_template(body, virtual_path: "test/foo/_customer") + assert_not template.eligible_for_collection_caching?, "Template #{body.inspect} should not be eligible for collection caching" + end + end + + def test_eligible_for_collection_caching_with_cache_call_or_explicit + [ + "<% cache customer do %><% end %>", + "<% cache(customer) do %><% end %>", + "<% cache( customer) do %><% end %>", + "<% cache( customer ) do %><% end %>", + "<%cache customer do %><% end %>", + "<% cache customer do %><% end %>", + " <% cache customer do %>\n<% end %>\n", + "<%# comment %><% cache customer do %><% end %>", + "<%# comment %>\n<% cache customer do %><% end %>", + "<%# comment\n line 2\n line 3 %>\n<% cache customer do %><% end %>", + "<%# comment 1 %>\n<%# comment 2 %>\n<% cache customer do %><% end %>", + "<%# comment 1 %>\n<%# Template Collection: customer %>\n<% my_cache customer do %><% end %>" + ].each do |body| + template = new_template(body, virtual_path: "test/foo/_customer") + assert template.eligible_for_collection_caching?, "Template #{body.inspect} should be eligible for collection caching" + end end def with_external_encoding(encoding) diff --git a/actionview/test/template/test_case_test.rb b/actionview/test/template/test_case_test.rb index 5ad1938b61..b057d43ee0 100644 --- a/actionview/test/template/test_case_test.rb +++ b/actionview/test/template/test_case_test.rb @@ -20,6 +20,7 @@ module ActionView class TestCase helper ASharedTestHelper + DeveloperStruct = Struct.new(:name) module SharedTests def self.included(test_case) @@ -50,7 +51,7 @@ module ActionView end test "works without testing a helper module" do - assert_equal 'Eloy', render('developers/developer', :developer => stub(:name => 'Eloy')) + assert_equal 'Eloy', render('developers/developer', :developer => DeveloperStruct.new('Eloy')) end test "can render a layout with block" do @@ -69,13 +70,15 @@ module ActionView end test "delegates notice to request.flash[:notice]" do - view.request.flash.expects(:[]).with(:notice) - view.notice + assert_called_with(view.request.flash, :[], [:notice]) do + view.notice + end end test "delegates alert to request.flash[:alert]" do - view.request.flash.expects(:[]).with(:alert) - view.alert + assert_called_with(view.request.flash, :[], [:alert]) do + view.alert + end end test "uses controller lookup context" do @@ -119,7 +122,7 @@ module ActionView test "helper class that is being tested is always included in view instance" do @controller.controller_path = 'test' - @customers = [stub(:name => 'Eloy'), stub(:name => 'Manfred')] + @customers = [DeveloperStruct.new('Eloy'), DeveloperStruct.new('Manfred')] assert_match(/Hello: EloyHello: Manfred/, render(:partial => 'test/from_helper')) end end @@ -209,7 +212,7 @@ module ActionView end test "is able to use routes" do - controller.request.assign_parameters(@routes, 'foo', 'index') + controller.request.assign_parameters(@routes, 'foo', 'index', {}, '/foo', []) assert_equal '/foo', url_for assert_equal '/bar', url_for(:controller => 'bar') end @@ -255,15 +258,15 @@ module ActionView end test "is able to render partials with local variables" do - assert_equal 'Eloy', render('developers/developer', :developer => stub(:name => 'Eloy')) + assert_equal 'Eloy', render('developers/developer', :developer => DeveloperStruct.new('Eloy')) assert_equal 'Eloy', render(:partial => 'developers/developer', - :locals => { :developer => stub(:name => 'Eloy') }) + :locals => { :developer => DeveloperStruct.new('Eloy') }) end test "is able to render partials from templates and also use instance variables" do @controller.controller_path = "test" - @customers = [stub(:name => 'Eloy'), stub(:name => 'Manfred')] + @customers = [DeveloperStruct.new('Eloy'), DeveloperStruct.new('Manfred')] assert_match(/Hello: EloyHello: Manfred/, render(:file => 'test/list')) end @@ -272,7 +275,7 @@ module ActionView view - @customers = [stub(:name => 'Eloy'), stub(:name => 'Manfred')] + @customers = [DeveloperStruct.new('Eloy'), DeveloperStruct.new('Manfred')] assert_match(/Hello: EloyHello: Manfred/, render(:file => 'test/list')) end @@ -306,63 +309,6 @@ module ActionView end end - class RenderTemplateTest < ActionView::TestCase - test "supports specifying templates with a Regexp" do - controller.controller_path = "fun" - render(:template => "fun/games/hello_world") - assert_template %r{\Afun/games/hello_world\Z} - end - - test "supports specifying partials" do - controller.controller_path = "test" - render(:template => "test/calling_partial_with_layout") - assert_template :partial => "_partial_for_use_in_layout" - end - - test "supports specifying locals (passing)" do - controller.controller_path = "test" - render(:template => "test/calling_partial_with_layout") - assert_template :partial => "_partial_for_use_in_layout", :locals => { :name => "David" } - end - - test "supports specifying locals (failing)" do - controller.controller_path = "test" - render(:template => "test/calling_partial_with_layout") - assert_raise ActiveSupport::TestCase::Assertion, /Somebody else.*David/m do - assert_template :partial => "_partial_for_use_in_layout", :locals => { :name => "Somebody Else" } - end - end - - test 'supports different locals on the same partial' do - controller.controller_path = "test" - render(:template => "test/render_two_partials") - assert_template partial: '_partial', locals: { 'first' => '1' } - assert_template partial: '_partial', locals: { 'second' => '2' } - end - - test 'raises descriptive error message when template was not rendered' do - controller.controller_path = "test" - render(template: "test/hello_world_with_partial") - e = assert_raise ActiveSupport::TestCase::Assertion do - assert_template partial: 'i_was_never_rendered', locals: { 'did_not' => 'happen' } - end - assert_match "i_was_never_rendered to be rendered but it was not.", e.message - assert_match 'Expected ["/test/partial"] to include "i_was_never_rendered"', e.message - end - - test 'specifying locals works when the partial is inside a directory with underline prefix' do - controller.controller_path = "test" - render(template: 'test/render_partial_inside_directory') - assert_template partial: 'test/_directory/_partial_with_locales', locals: { 'name' => 'Jane' } - end - - test 'specifying locals works when the partial is inside a directory without underline prefix' do - controller.controller_path = "test" - render(template: 'test/render_partial_inside_directory') - assert_template partial: 'test/_directory/partial_with_locales', locals: { 'name' => 'Jane' } - end - end - module AHelperWithInitialize def initialize(*) super diff --git a/actionview/test/template/text_helper_test.rb b/actionview/test/template/text_helper_test.rb index f05b845e46..fae1965ffa 100644 --- a/actionview/test/template/text_helper_test.rb +++ b/actionview/test/template/text_helper_test.rb @@ -1,4 +1,3 @@ -# encoding: utf-8 require 'abstract_unit' class TextHelperTest < ActionView::TestCase @@ -367,6 +366,10 @@ class TextHelperTest < ActionView::TestCase assert_equal options, passed_options end + def test_word_wrap_with_custom_break_sequence + assert_equal("1234567890\r\n1234567890\r\n1234567890", word_wrap("1234567890 " * 3, line_width: 2, break_sequence: "\r\n")) + end + def test_pluralization assert_equal("1 count", pluralize(1, "count")) assert_equal("2 counts", pluralize(2, "count")) @@ -384,6 +387,18 @@ class TextHelperTest < ActionView::TestCase assert_equal("12 berries", pluralize(12, "berry")) end + def test_pluralization_with_locale + ActiveSupport::Inflector.inflections(:de) do |inflect| + inflect.plural(/(person)$/i, '\1en') + inflect.singular(/(person)en$/i, '\1') + end + + assert_equal("2 People", pluralize(2, "Person", locale: :en)) + assert_equal("2 Personen", pluralize(2, "Person", locale: :de)) + + ActiveSupport::Inflector.inflections(:de).clear + end + def test_cycle_class value = Cycle.new("one", 2, "3") assert_equal("one", value.to_s) diff --git a/actionview/test/template/translation_helper_test.rb b/actionview/test/template/translation_helper_test.rb index 362f05ea70..749d0dd7fd 100644 --- a/actionview/test/template/translation_helper_test.rb +++ b/actionview/test/template/translation_helper_test.rb @@ -1,5 +1,13 @@ require 'abstract_unit' +module I18n + class CustomExceptionHandler + def self.call(exception, locale, key, options) + 'from CustomExceptionHandler' + end + end +end + class TranslationHelperTest < ActiveSupport::TestCase include ActionView::Helpers::TranslationHelper @@ -33,15 +41,17 @@ class TranslationHelperTest < ActiveSupport::TestCase I18n.backend.reload! end - def test_delegates_to_i18n_setting_the_rescue_format_option_to_html - I18n.expects(:translate).with(:foo, :locale => 'en', :raise=>true).returns("") - translate :foo, :locale => 'en' + def test_delegates_setting_to_i18n + assert_called_with(I18n, :translate, [:foo, :locale => 'en', :raise => true], returns: "") do + translate :foo, :locale => 'en' + end end def test_delegates_localize_to_i18n @time = Time.utc(2008, 7, 8, 12, 18, 38) - I18n.expects(:localize).with(@time) - localize @time + assert_called_with(I18n, :localize, [@time]) do + localize @time + end end def test_returns_missing_translation_message_wrapped_into_span @@ -50,12 +60,6 @@ class TranslationHelperTest < ActiveSupport::TestCase assert_equal true, translate(:"translations.missing").html_safe? end - def test_returns_missing_translation_message_using_nil_as_rescue_format - expected = 'translation missing: en.translations.missing' - assert_equal expected, translate(:"translations.missing", :rescue_format => nil) - assert_equal false, translate(:"translations.missing", :rescue_format => nil).html_safe? - end - def test_raises_missing_translation_message_with_raise_config_option ActionView::Base.raise_on_missing_translations = true @@ -72,10 +76,20 @@ class TranslationHelperTest < ActiveSupport::TestCase end end - def test_i18n_translate_defaults_to_nil_rescue_format - expected = 'translation missing: en.translations.missing' - assert_equal expected, I18n.translate(:"translations.missing") - assert_equal false, I18n.translate(:"translations.missing").html_safe? + def test_uses_custom_exception_handler_when_specified + old_exception_handler = I18n.exception_handler + I18n.exception_handler = I18n::CustomExceptionHandler + assert_equal 'from CustomExceptionHandler', translate(:"translations.missing", raise: false) + ensure + I18n.exception_handler = old_exception_handler + end + + def test_uses_custom_exception_handler_when_specified_for_html + old_exception_handler = I18n.exception_handler + I18n.exception_handler = I18n::CustomExceptionHandler + assert_equal 'from CustomExceptionHandler', translate(:"translations.missing_html", raise: false) + ensure + I18n.exception_handler = old_exception_handler end def test_translation_returning_an_array @@ -113,8 +127,9 @@ class TranslationHelperTest < ActiveSupport::TestCase end def test_translate_escapes_interpolations_in_translations_with_a_html_suffix + word_struct = Struct.new(:to_s) assert_equal '<a>Hello <World></a>', translate(:'translations.interpolated_html', :word => '<World>') - assert_equal '<a>Hello <World></a>', translate(:'translations.interpolated_html', :word => stub(:to_s => "<World>")) + assert_equal '<a>Hello <World></a>', translate(:'translations.interpolated_html', :word => word_struct.new("<World>")) end def test_translate_with_html_count @@ -133,6 +148,19 @@ class TranslationHelperTest < ActiveSupport::TestCase assert_equal true, translation.html_safe? end + def test_translate_with_missing_default + translation = translate(:'translations.missing', :default => :'translations.missing_html') + expected = '<span class="translation_missing" title="translation missing: en.translations.missing_html">Missing Html</span>' + assert_equal expected, translation + assert_equal true, translation.html_safe? + end + + def test_translate_with_missing_default_and_raise_option + assert_raise(I18n::MissingTranslationData) do + translate(:'translations.missing', :default => :'translations.missing_html', :raise => true) + end + end + def test_translate_with_two_defaults_named_html translation = translate(:'translations.missing', :default => [:'translations.missing_html', :'translations.hello_html']) assert_equal '<a>Hello World</a>', translation @@ -145,16 +173,37 @@ class TranslationHelperTest < ActiveSupport::TestCase assert_equal true, translation.html_safe? end + def test_translate_with_last_default_not_named_html + translation = translate(:'translations.missing', :default => [:'translations.missing_html', :'translations.foo']) + assert_equal 'Foo', translation + assert_equal false, translation.html_safe? + end + def test_translate_with_string_default translation = translate(:'translations.missing', default: 'A Generic String') assert_equal 'A Generic String', translation end + def test_translate_with_object_default + translation = translate(:'translations.missing', default: 123) + assert_equal 123, translation + end + def test_translate_with_array_of_string_defaults translation = translate(:'translations.missing', default: ['A Generic String', 'Second generic string']) assert_equal 'A Generic String', translation end + def test_translate_with_array_of_defaults_with_nil + translation = translate(:'translations.missing', default: [:'also_missing', nil, 'A Generic String']) + assert_equal 'A Generic String', translation + end + + def test_translate_with_array_of_array_default + translation = translate(:'translations.missing', default: [[]]) + assert_equal [], translation + end + def test_translate_does_not_change_options options = {} translate(:'translations.missing', options) diff --git a/actionview/test/template/url_helper_test.rb b/actionview/test/template/url_helper_test.rb index e0678ae1f7..027b72b354 100644 --- a/actionview/test/template/url_helper_test.rb +++ b/actionview/test/template/url_helper_test.rb @@ -1,6 +1,4 @@ -# encoding: utf-8 require 'abstract_unit' -require 'minitest/mock' class UrlHelperTest < ActiveSupport::TestCase @@ -380,6 +378,11 @@ class UrlHelperTest < ActiveSupport::TestCase assert_dom_equal %{<a href="/">Listing</a>}, link_to_if(true, "Listing", url_hash) end + def test_link_to_if_with_block + assert_equal "Fallback", link_to_if(false, "Showing", url_hash) { "Fallback" } + assert_dom_equal %{<a href="/">Listing</a>}, link_to_if(true, "Listing", url_hash) { "Fallback" } + end + def request_for_url(url, opts = {}) env = Rack::MockRequest.env_for("http://www.example.com#{url}", opts) ActionDispatch::Request.new(env) @@ -480,6 +483,11 @@ class UrlHelperTest < ActiveSupport::TestCase link_to_unless_current("Listing", "http://www.example.com/") end + def test_link_to_unless_with_block + assert_dom_equal %{<a href="/">Showing</a>}, link_to_unless(false, "Showing", url_hash) { "Fallback" } + assert_equal "Fallback", link_to_unless(true, "Listing", url_hash) { "Fallback" } + end + def test_mail_to assert_dom_equal %{<a href="mailto:david@loudthinking.com">david@loudthinking.com</a>}, mail_to("david@loudthinking.com") assert_dom_equal %{<a href="mailto:david@loudthinking.com">David Heinemeier Hansson</a>}, mail_to("david@loudthinking.com", "David Heinemeier Hansson") @@ -491,10 +499,22 @@ class UrlHelperTest < ActiveSupport::TestCase mail_to("david@loudthinking.com", "David Heinemeier Hansson", class: "admin") end + def test_mail_to_with_special_characters + assert_dom_equal( + %{<a href="mailto:%23%21%24%25%26%27%2A%2B-%2F%3D%3F%5E_%60%7B%7D%7C%7E@example.org">#!$%&'*+-/=?^_`{}|~@example.org</a>}, + mail_to("#!$%&'*+-/=?^_`{}|~@example.org") + ) + end + def test_mail_with_options assert_dom_equal( - %{<a href="mailto:me@example.com?cc=ccaddress%40example.com&bcc=bccaddress%40example.com&body=This%20is%20the%20body%20of%20the%20message.&subject=This%20is%20an%20example%20email">My email</a>}, - mail_to("me@example.com", "My email", cc: "ccaddress@example.com", bcc: "bccaddress@example.com", subject: "This is an example email", body: "This is the body of the message.") + %{<a href="mailto:me@example.com?cc=ccaddress%40example.com&bcc=bccaddress%40example.com&body=This%20is%20the%20body%20of%20the%20message.&subject=This%20is%20an%20example%20email&reply-to=foo%40bar.com">My email</a>}, + mail_to("me@example.com", "My email", cc: "ccaddress@example.com", bcc: "bccaddress@example.com", subject: "This is an example email", body: "This is the body of the message.", reply_to: "foo@bar.com") + ) + + assert_dom_equal( + %{<a href="mailto:me@example.com?body=This%20is%20the%20body%20of%20the%20message.&subject=This%20is%20an%20example%20email">My email</a>}, + mail_to("me@example.com", "My email", cc: '', bcc: '', subject: "This is an example email", body: "This is the body of the message.") ) end @@ -624,13 +644,13 @@ class UrlHelperControllerTest < ActionController::TestCase end def test_named_route_url_shows_host_and_path - get :show_named_route, kind: 'url' + get :show_named_route, params: { kind: 'url' } assert_equal 'http://test.host/url_helper_controller_test/url_helper/show_named_route', @response.body end def test_named_route_path_shows_only_path - get :show_named_route, kind: 'path' + get :show_named_route, params: { kind: 'path' } assert_equal '/url_helper_controller_test/url_helper/show_named_route', @response.body end @@ -646,7 +666,7 @@ class UrlHelperControllerTest < ActionController::TestCase end end - get :show_named_route, kind: 'url' + get :show_named_route, params: { kind: 'url' } assert_equal 'http://testtwo.host/url_helper_controller_test/url_helper/show_named_route', @response.body end @@ -661,11 +681,11 @@ class UrlHelperControllerTest < ActionController::TestCase end def test_recall_params_should_normalize_id - get :show, id: '123' + get :show, params: { id: '123' } assert_equal 302, @response.status assert_equal 'http://test.host/url_helper_controller_test/url_helper/profile/123', @response.location - get :show, name: '123' + get :show, params: { name: '123' } assert_equal 'ok', @response.body end @@ -704,7 +724,7 @@ class LinkToUnlessCurrentWithControllerTest < ActionController::TestCase end def test_link_to_unless_current_shows_link - get :show, id: 1 + get :show, params: { id: 1 } assert_equal %{<a href="/tasks">tasks</a>\n} + %{<a href="#{@request.protocol}#{@request.host_with_port}/tasks">tasks</a>}, @response.body @@ -778,21 +798,21 @@ class PolymorphicControllerTest < ActionController::TestCase def test_existing_resource @controller = WorkshopsController.new - get :show, id: 1 + get :show, params: { id: 1 } assert_equal %{/workshops/1\n<a href="/workshops/1">Workshop</a>}, @response.body end def test_new_nested_resource @controller = SessionsController.new - get :index, workshop_id: 1 + get :index, params: { workshop_id: 1 } assert_equal %{/workshops/1/sessions\n<a href="/workshops/1/sessions">Session</a>}, @response.body end def test_existing_nested_resource @controller = SessionsController.new - get :show, workshop_id: 1, id: 1 + get :show, params: { workshop_id: 1, id: 1 } assert_equal %{/workshops/1/sessions/1\n<a href="/workshops/1/sessions/1">Session</a>}, @response.body end end |