diff options
Diffstat (limited to 'actionview/test')
121 files changed, 21512 insertions, 3252 deletions
diff --git a/actionview/test/abstract_unit.rb b/actionview/test/abstract_unit.rb index 3256d8fc4d..f20a66c2d2 100644 --- a/actionview/test/abstract_unit.rb +++ b/actionview/test/abstract_unit.rb @@ -1,36 +1,30 @@ -$:.unshift(File.dirname(__FILE__) + '/lib') -$:.unshift(File.dirname(__FILE__) + '/fixtures/helpers') -$:.unshift(File.dirname(__FILE__) + '/fixtures/alternate_helpers') +# frozen_string_literal: true -ENV['TMPDIR'] = File.join(File.dirname(__FILE__), 'tmp') +$:.unshift File.expand_path("lib", __dir__) +$:.unshift File.expand_path("fixtures/helpers", __dir__) +$:.unshift File.expand_path("fixtures/alternate_helpers", __dir__) -require 'active_support/core_ext/kernel/reporting' +ENV["TMPDIR"] = File.expand_path("tmp", __dir__) + +require "active_support/core_ext/kernel/reporting" # These are the normal settings that will be set up by Railties # TODO: Have these tests support other combinations of these values silence_warnings do - Encoding.default_internal = "UTF-8" - Encoding.default_external = "UTF-8" + Encoding.default_internal = Encoding::UTF_8 + Encoding.default_external = Encoding::UTF_8 end -require 'active_support/testing/autorun' -require 'active_support/testing/method_call_assertions' -require 'action_controller' -require 'action_view' -require 'action_view/testing/resolvers' -require 'active_support/dependencies' -require 'active_model' -require 'active_record' - -require 'pp' # require 'pp' early to prevent hidden_methods from not picking up the pretty-print methods until too late - -module Rails - class << self - def env - @_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "test") - end - end -end +require "active_support/testing/autorun" +require "active_support/testing/method_call_assertions" +require "action_controller" +require "action_view" +require "action_view/testing/resolvers" +require "active_support/dependencies" +require "active_model" +require "active_record" + +require "pp" # require 'pp' early to prevent hidden_methods from not picking up the pretty-print methods until too late ActiveSupport::Dependencies.hook! @@ -43,11 +37,11 @@ ActiveSupport::Deprecation.debug = true I18n.enforce_available_locales = false # Register danish language for testing -I18n.backend.store_translations 'da', {} -I18n.backend.store_translations 'pt-BR', {} +I18n.backend.store_translations "da", {} +I18n.backend.store_translations "pt-BR", {} ORIGINAL_LOCALES = I18n.available_locales.map(&:to_s).sort -FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures') +FIXTURE_LOAD_PATH = File.expand_path("fixtures", __dir__) module RenderERBUtils def view @@ -95,11 +89,11 @@ module ActionDispatch ActiveSupport::Deprecation.silence do SharedTestRoutes.draw do - get ':controller(/:action)' + get ":controller(/:action)" end ActionDispatch::IntegrationTest.app.routes.draw do - get ':controller(/:action)' + get ":controller(/:action)" end end @@ -108,12 +102,6 @@ module ActionDispatch end end -module ActiveSupport - class TestCase - include ActionDispatch::DrawOnce - end -end - class RoutedRackApp attr_reader :routes @@ -133,11 +121,11 @@ class BasicController def config @config ||= ActiveSupport::InheritableOptions.new(ActionController::Base.config).tap do |config| # VIEW TODO: View tests should not require a controller - public_dir = File.expand_path("../fixtures/public", __FILE__) + public_dir = File.expand_path("fixtures/public", __dir__) config.assets_dir = public_dir config.javascripts_dir = "#{public_dir}/javascripts" config.stylesheets_dir = "#{public_dir}/stylesheets" - config.assets = ActiveSupport::InheritableOptions.new({ :prefix => "assets" }) + config.assets = ActiveSupport::InheritableOptions.new(prefix: "assets") config end end @@ -160,29 +148,6 @@ class ActionDispatch::IntegrationTest < ActiveSupport::TestCase self.app = build_app - # Stub Rails dispatcher so it does not get controller references and - # simply return the controller#action as Rack::Body. - class StubDispatcher < ::ActionDispatch::Routing::RouteSet::Dispatcher - protected - def controller_reference(controller_param) - controller_param - end - - def dispatch(controller, action, env) - [200, {'Content-Type' => 'text/html'}, ["#{controller}##{action}"]] - end - end - - def self.stub_controllers - old_dispatcher = ActionDispatch::Routing::RouteSet::Dispatcher - ActionDispatch::Routing::RouteSet.module_eval { remove_const :Dispatcher } - ActionDispatch::Routing::RouteSet.module_eval { const_set :Dispatcher, StubDispatcher } - yield ActionDispatch::Routing::RouteSet.new - ensure - ActionDispatch::Routing::RouteSet.module_eval { remove_const :Dispatcher } - ActionDispatch::Routing::RouteSet.module_eval { const_set :Dispatcher, old_dispatcher } - end - def with_routing(&block) temporary_routes = ActionDispatch::Routing::RouteSet.new old_app, self.class.app = self.class.app, self.class.build_app(temporary_routes) @@ -194,21 +159,6 @@ class ActionDispatch::IntegrationTest < ActiveSupport::TestCase self.class.app = old_app silence_warnings { Object.const_set(:SharedTestRoutes, old_routes) } end - - def with_autoload_path(path) - path = File.join(File.dirname(__FILE__), "fixtures", path) - if ActiveSupport::Dependencies.autoload_paths.include?(path) - yield - else - begin - ActiveSupport::Dependencies.autoload_paths << path - yield - ensure - ActiveSupport::Dependencies.autoload_paths.reject! {|p| p == path} - ActiveSupport::Dependencies.clear - end - end - end end ActionView::RoutingUrlFor.include(ActionDispatch::Routing::UrlFor) @@ -263,23 +213,24 @@ end module ActionDispatch class DebugExceptions private - remove_method :stderr_logger - # Silence logger - def stderr_logger - nil - end + remove_method :stderr_logger + # Silence logger + def stderr_logger + nil + end end end -# Skips the current run on Rubinius using Minitest::Assertions#skip -def rubinius_skip(message = '') - skip message if RUBY_ENGINE == 'rbx' -end -# Skips the current run on JRuby using Minitest::Assertions#skip -def jruby_skip(message = '') - skip message if defined?(JRUBY_VERSION) -end - class ActiveSupport::TestCase + include ActionDispatch::DrawOnce include ActiveSupport::Testing::MethodCallAssertions + + # Skips the current run on Rubinius using Minitest::Assertions#skip + private def rubinius_skip(message = "") + skip message if RUBY_ENGINE == "rbx" + end + # Skips the current run on JRuby using Minitest::Assertions#skip + private def jruby_skip(message = "") + skip message if defined?(JRUBY_VERSION) + end end diff --git a/actionview/test/actionpack/abstract/abstract_controller_test.rb b/actionview/test/actionpack/abstract/abstract_controller_test.rb index 490932fef0..4d4e2b8ef2 100644 --- a/actionview/test/actionpack/abstract/abstract_controller_test.rb +++ b/actionview/test/actionpack/abstract/abstract_controller_test.rb @@ -1,9 +1,10 @@ -require 'abstract_unit' -require 'set' +# frozen_string_literal: true + +require "abstract_unit" +require "set" module AbstractController module Testing - # Test basic dispatching. # ==== # * Call process @@ -38,12 +39,12 @@ module AbstractController def render(options = {}) if options.is_a?(String) - options = {:_template_name => options} + options = { _template_name: options } end super end - append_view_path File.expand_path(File.join(File.dirname(__FILE__), "views")) + append_view_path File.expand_path("views", __dir__) end class Me2 < RenderingController @@ -65,11 +66,11 @@ module AbstractController end def rendering_to_body - self.response_body = render_to_body :template => "naked_render" + self.response_body = render_to_body template: "naked_render" end def rendering_to_string - self.response_body = render_to_string :template => "naked_render" + self.response_body = render_to_string template: "naked_render" end end @@ -114,13 +115,13 @@ module AbstractController # * self._prefix is used when defined class PrefixedViews < RenderingController private - def self.prefix - name.underscore - end + def self.prefix + name.underscore + end - def _prefixes - [self.class.prefix] - end + def _prefixes + [self.class.prefix] + end end class Me3 < PrefixedViews @@ -153,7 +154,7 @@ module AbstractController class OverridingLocalPrefixes < AbstractController::Base include AbstractController::Rendering include ActionView::Rendering - append_view_path File.expand_path(File.join(File.dirname(__FILE__), "views")) + append_view_path File.expand_path("views", __dir__) def index render @@ -189,19 +190,19 @@ module AbstractController include ActionView::Layouts private - def self.layout(formats) - find_template(name.underscore, {:formats => formats}, :_prefixes => ["layouts"]) - rescue ActionView::MissingTemplate - begin - find_template("application", {:formats => formats}, :_prefixes => ["layouts"]) + def self.layout(formats) + find_template(name.underscore, { formats: formats }, { _prefixes: ["layouts"] }) rescue ActionView::MissingTemplate + begin + find_template("application", { formats: formats }, { _prefixes: ["layouts"] }) + rescue ActionView::MissingTemplate + end end - end - def render_to_body(options = {}) - options[:_layout] = options[:layout] || _default_layout({}) - super - end + def render_to_body(options = {}) + options[:_layout] = options[:layout] || _default_layout({}) + super + end end class Me4 < WithLayouts @@ -228,14 +229,14 @@ module AbstractController end class ActionMissingRespondToActionController < AbstractController::Base - # No actions + # No actions private def action_missing(action_name) self.response_body = "success" end end - class RespondToActionController < AbstractController::Base; + class RespondToActionController < AbstractController::Base def index() self.response_body = "success" end def fail() self.response_body = "fail" end @@ -248,7 +249,6 @@ module AbstractController end class TestRespondToAction < ActiveSupport::TestCase - def assert_dispatch(klass, body = "success", action = :index) controller = klass.new controller.process(action) @@ -277,18 +277,16 @@ module AbstractController end class Me6 < AbstractController::Base - self.action_methods + action_methods def index end end class TestActionMethodsReloading < ActiveSupport::TestCase - test "action_methods should be reloaded after defining a new method" do assert_equal Set.new(["index"]), Me6.action_methods end end - end end diff --git a/actionview/test/actionpack/abstract/helper_test.rb b/actionview/test/actionpack/abstract/helper_test.rb index 7d346e917d..480ff60ba2 100644 --- a/actionview/test/actionpack/abstract/helper_test.rb +++ b/actionview/test/actionpack/abstract/helper_test.rb @@ -1,17 +1,18 @@ -require 'abstract_unit' +# frozen_string_literal: true -ActionController::Base.helpers_path = File.expand_path('../../../fixtures/helpers', __FILE__) +require "abstract_unit" + +ActionController::Base.helpers_path = File.expand_path("../../fixtures/helpers", __dir__) module AbstractController module Testing - class ControllerWithHelpers < AbstractController::Base include AbstractController::Helpers include AbstractController::Rendering include ActionView::Rendering def with_module - render :inline => "Module <%= included_method %>" + render inline: "Module <%= included_method %>" end end @@ -31,11 +32,11 @@ module AbstractController helper :abc def with_block - render :inline => "Hello <%= helpery_test %>" + render inline: "Hello <%= helpery_test %>" end def with_symbol - render :inline => "I respond to bare_a: <%= respond_to?(:bare_a) %>" + render inline: "I respond to bare_a: <%= respond_to?(:bare_a) %>" end end @@ -52,7 +53,7 @@ module AbstractController class AbstractInvalidHelpers < AbstractHelpers include ActionController::Helpers - path = File.expand_path('../../../fixtures/helpers_missing', __FILE__) + path = File.expand_path("../../fixtures/helpers_missing", __dir__) $:.unshift(path) self.helpers_path = path end @@ -110,7 +111,7 @@ module AbstractController class InvalidHelpersTest < ActiveSupport::TestCase def test_controller_raise_error_about_real_require_problem e = assert_raise(LoadError) { AbstractInvalidHelpers.helper(:invalid_require) } - assert_equal "No such file to load -- very_invalid_file_name", e.message + assert_equal "No such file to load -- very_invalid_file_name.rb", e.message end def test_controller_raise_error_about_missing_helper diff --git a/actionview/test/actionpack/abstract/layouts_test.rb b/actionview/test/actionpack/abstract/layouts_test.rb index 80bc665b0a..1146e6f64b 100644 --- a/actionview/test/actionpack/abstract/layouts_test.rb +++ b/actionview/test/actionpack/abstract/layouts_test.rb @@ -1,8 +1,9 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" module AbstractControllerTests module Layouts - # Base controller for these tests class Base < AbstractController::Base include AbstractController::Rendering @@ -12,7 +13,9 @@ module AbstractControllerTests abstract! self.view_paths = [ActionView::FixtureResolver.new( + "some/template.erb" => "hello <%= foo %> bar", "layouts/hello.erb" => "With String <%= yield %>", + "layouts/hello_locals.erb" => "With String <%= yield %>", "layouts/hello_override.erb" => "With Override <%= yield %>", "layouts/overwrite.erb" => "Overwrite <%= yield %>", "layouts/with_false_layout.erb" => "False Layout <%= yield %>", @@ -28,7 +31,15 @@ module AbstractControllerTests self.view_paths = [] def index - render :template => ActionView::Template::Text.new("Hello blank!") + render template: ActionView::Template::Text.new("Hello blank!") + end + end + + class WithStringLocals < Base + layout "hello_locals" + + def index + render template: "some/template", locals: { foo: "less than 3" } end end @@ -36,19 +47,23 @@ module AbstractControllerTests layout "hello" def index - render :template => ActionView::Template::Text.new("Hello string!") + render template: ActionView::Template::Text.new("Hello string!") + end + + def action_has_layout_false + render template: ActionView::Template::Text.new("Hello string!") end def overwrite_default - render :template => ActionView::Template::Text.new("Hello string!"), :layout => :default + render template: ActionView::Template::Text.new("Hello string!"), layout: :default end def overwrite_false - render :template => ActionView::Template::Text.new("Hello string!"), :layout => false + render template: ActionView::Template::Text.new("Hello string!"), layout: false end def overwrite_string - render :template => ActionView::Template::Text.new("Hello string!"), :layout => "overwrite" + render template: ActionView::Template::Text.new("Hello string!"), layout: "overwrite" end def overwrite_skip @@ -78,11 +93,11 @@ module AbstractControllerTests layout proc { "overwrite" } def index - render :template => ActionView::Template::Text.new("Hello proc!") + render template: ActionView::Template::Text.new("Hello proc!") end end - class WithProcReturningNil < Base + class WithProcReturningNil < WithString layout proc { nil } def index @@ -90,11 +105,19 @@ module AbstractControllerTests end end + class WithProcReturningFalse < WithString + layout proc { false } + + def index + render template: ActionView::Template::Text.new("Hello false!") + end + end + class WithZeroArityProc < Base layout proc { "overwrite" } def index - render :template => ActionView::Template::Text.new("Hello zero arity proc!") + render template: ActionView::Template::Text.new("Hello zero arity proc!") end end @@ -107,7 +130,7 @@ module AbstractControllerTests } def index - render :template => ActionView::Template::Text.new("Hello again zero arity proc!") + render template: ActionView::Template::Text.new("Hello again zero arity proc!") end end @@ -115,7 +138,7 @@ module AbstractControllerTests layout :hello def index - render :template => ActionView::Template::Text.new("Hello symbol!") + render template: ActionView::Template::Text.new("Hello symbol!") end private def hello @@ -127,7 +150,7 @@ module AbstractControllerTests layout :nilz def index - render :template => ActionView::Template::Text.new("Hello nilz!") + render template: ActionView::Template::Text.new("Hello nilz!") end def nilz() end @@ -137,7 +160,7 @@ module AbstractControllerTests layout :objekt def index - render :template => ActionView::Template::Text.new("Hello nilz!") + render template: ActionView::Template::Text.new("Hello nilz!") end def objekt @@ -149,7 +172,7 @@ module AbstractControllerTests layout :no_method def index - render :template => ActionView::Template::Text.new("Hello boom!") + render template: ActionView::Template::Text.new("Hello boom!") end end @@ -157,7 +180,7 @@ module AbstractControllerTests layout "missing" def index - render :template => ActionView::Template::Text.new("Hello missing!") + render template: ActionView::Template::Text.new("Hello missing!") end end @@ -165,7 +188,7 @@ module AbstractControllerTests layout false def index - render :template => ActionView::Template::Text.new("Hello false!") + render template: ActionView::Template::Text.new("Hello false!") end end @@ -173,34 +196,81 @@ module AbstractControllerTests layout nil def index - render :template => ActionView::Template::Text.new("Hello nil!") + render template: ActionView::Template::Text.new("Hello nil!") end end class WithOnlyConditional < WithStringImpliedChild - layout "overwrite", :only => :show + layout "overwrite", only: :show def index - render :template => ActionView::Template::Text.new("Hello index!") + render template: ActionView::Template::Text.new("Hello index!") end def show - render :template => ActionView::Template::Text.new("Hello show!") + render template: ActionView::Template::Text.new("Hello show!") end end + class WithOnlyConditionalFlipped < WithOnlyConditional + layout "hello_override", only: :index + end + + class WithOnlyConditionalFlippedAndInheriting < WithOnlyConditional + layout nil, only: :index + end + class WithExceptConditional < WithStringImpliedChild - layout "overwrite", :except => :show + layout "overwrite", except: :show def index - render :template => ActionView::Template::Text.new("Hello index!") + render template: ActionView::Template::Text.new("Hello index!") end def show - render :template => ActionView::Template::Text.new("Hello show!") + render template: ActionView::Template::Text.new("Hello show!") + end + end + + class AbstractWithString < Base + layout "hello" + abstract! + end + + class AbstractWithStringChild < AbstractWithString + def index + render template: ActionView::Template::Text.new("Hello abstract child!") end end + class AbstractWithStringChildDefaultsToInherited < AbstractWithString + layout nil + + def index + render template: ActionView::Template::Text.new("Hello abstract child!") + end + end + + class WithConditionalOverride < WithString + layout "overwrite", only: :overwritten + + def non_overwritten + render template: ActionView::Template::Text.new("Hello non overwritten!") + end + + def overwritten + render template: ActionView::Template::Text.new("Hello overwritten!") + end + end + + class WithConditionalOverrideFlipped < WithConditionalOverride + layout "hello_override", only: :non_overwritten + end + + class WithConditionalOverrideFlippedAndInheriting < WithConditionalOverride + layout nil, only: :non_overwritten + end + class TestBase < ActiveSupport::TestCase test "when no layout is specified, and no default is available, render without a layout" do controller = Blank.new @@ -208,6 +278,31 @@ module AbstractControllerTests assert_equal "Hello blank!", controller.response_body end + test "with locals" do + controller = WithStringLocals.new + controller.process(:index) + assert_equal "With String hello less than 3 bar", controller.response_body + end + + test "cache should not grow when locals change for a string template" do + cache = WithString.view_paths.paths.first.instance_variable_get(:@cache) + + controller = WithString.new + controller.process(:index) # heat the cache + + size = cache.size + + 10.times do |x| + controller = WithString.new + controller.define_singleton_method :index do + render template: ActionView::Template::Text.new("Hello string!"), locals: { :"x#{x}" => :omg } + end + controller.process(:index) + end + + assert_equal size, cache.size + end + test "when layout is specified as a string, render with that layout" do controller = WithString.new controller.process(:index) @@ -255,7 +350,7 @@ module AbstractControllerTests end test "when layout is specified as a proc, do not leak any methods into controller's action_methods" do - assert_equal Set.new(['index']), WithProc.action_methods + assert_equal Set.new(["index"]), WithProc.action_methods end test "when layout is specified as a proc, call it and use the layout returned" do @@ -264,10 +359,16 @@ module AbstractControllerTests assert_equal "Overwrite Hello proc!", controller.response_body end - test "when layout is specified as a proc and the proc returns nil, don't use a layout" do + test "when layout is specified as a proc and the proc returns nil, use inherited layout" do controller = WithProcReturningNil.new controller.process(:index) - assert_equal "Hello nil!", controller.response_body + assert_equal "With String Hello nil!", controller.response_body + end + + test "when layout is specified as a proc and the proc returns false, use no layout instead of inherited layout" do + controller = WithProcReturningFalse.new + controller.process(:index) + assert_equal "Hello false!", controller.response_body end test "when layout is specified as a proc without parameters it works just the same" do @@ -322,16 +423,28 @@ module AbstractControllerTests test "when a grandchild has no layout specified, the child has an implied layout, and the " \ "parent has specified a layout, use the child controller layout" do - controller = WithChildOfImplied.new - controller.process(:index) - assert_equal "With Implied Hello string!", controller.response_body + controller = WithChildOfImplied.new + controller.process(:index) + assert_equal "With Implied Hello string!", controller.response_body end test "when a grandchild has nil layout specified, the child has an implied layout, and the " \ - "parent has specified a layout, use the child controller layout" do - controller = WithGrandChildOfImplied.new - controller.process(:index) - assert_equal "With Grand Child Hello string!", controller.response_body + "parent has specified a layout, use the grand child controller layout" do + controller = WithGrandChildOfImplied.new + controller.process(:index) + assert_equal "With Grand Child Hello string!", controller.response_body + end + + test "a child inherits layout from abstract controller" do + controller = AbstractWithStringChild.new + controller.process(:index) + assert_equal "With String Hello abstract child!", controller.response_body + end + + test "a child inherits layout from abstract controller2" do + controller = AbstractWithStringChildDefaultsToInherited.new + controller.process(:index) + assert_equal "With String Hello abstract child!", controller.response_body end test "raises an exception when specifying layout true" do @@ -356,6 +469,30 @@ module AbstractControllerTests assert_equal "With Implied Hello index!", controller.response_body end + test "when specify an :only option which match current action name and is opposite from parent controller" do + controller = WithOnlyConditionalFlipped.new + controller.process(:show) + assert_equal "With Implied Hello show!", controller.response_body + end + + test "when specify an :only option which does not match current action name and is opposite from parent controller" do + controller = WithOnlyConditionalFlipped.new + controller.process(:index) + assert_equal "With Override Hello index!", controller.response_body + end + + test "when specify to inherit and an :only option which match current action name and is opposite from parent controller" do + controller = WithOnlyConditionalFlippedAndInheriting.new + controller.process(:show) + assert_equal "With Implied Hello show!", controller.response_body + end + + test "when specify to inherit and an :only option which does not match current action name and is opposite from parent controller" do + controller = WithOnlyConditionalFlippedAndInheriting.new + controller.process(:index) + assert_equal "Overwrite Hello index!", controller.response_body + end + test "when specify an :except option which match current action name" do controller = WithExceptConditional.new controller.process(:show) @@ -368,10 +505,46 @@ module AbstractControllerTests assert_equal "Overwrite Hello index!", controller.response_body end + test "when specify overwrite as an :only option which match current action name" do + controller = WithConditionalOverride.new + controller.process(:overwritten) + assert_equal "Overwrite Hello overwritten!", controller.response_body + end + + test "when specify overwrite as an :only option which does not match current action name" do + controller = WithConditionalOverride.new + controller.process(:non_overwritten) + assert_equal "Hello non overwritten!", controller.response_body + end + + test "when specify overwrite as an :only option which match current action name and is opposite from parent controller" do + controller = WithConditionalOverrideFlipped.new + controller.process(:overwritten) + assert_equal "Hello overwritten!", controller.response_body + end + + test "when specify overwrite as an :only option which does not match current action name and is opposite from parent controller" do + controller = WithConditionalOverrideFlipped.new + controller.process(:non_overwritten) + assert_equal "With Override Hello non overwritten!", controller.response_body + end + + test "when specify to inherit and overwrite as an :only option which match current action name and is opposite from parent controller" do + controller = WithConditionalOverrideFlippedAndInheriting.new + controller.process(:overwritten) + assert_equal "Hello overwritten!", controller.response_body + end + + test "when specify to inherit and overwrite as an :only option which does not match current action name and is opposite from parent controller" do + controller = WithConditionalOverrideFlippedAndInheriting.new + controller.process(:non_overwritten) + assert_equal "Overwrite Hello non overwritten!", controller.response_body + end + test "layout for anonymous controller" do klass = Class.new(WithString) do def index - render plain: 'index', layout: true + render plain: "index", layout: true end end @@ -379,6 +552,17 @@ module AbstractControllerTests controller.process(:index) assert_equal "With String index", controller.response_body end + + test "when layout is disabled with #action_has_layout? returning false, render no layout" do + controller = WithString.new + controller.instance_eval do + def action_has_layout? + false + end + end + controller.process(:action_has_layout_false) + assert_equal "Hello string!", controller.response_body + end end end end diff --git a/actionview/test/actionpack/abstract/render_test.rb b/actionview/test/actionpack/abstract/render_test.rb index e185b76adb..d863548a5c 100644 --- a/actionview/test/actionpack/abstract/render_test.rb +++ b/actionview/test/actionpack/abstract/render_test.rb @@ -1,8 +1,9 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" module AbstractController module Testing - class ControllerRenderer < AbstractController::Base include AbstractController::Rendering include ActionView::Rendering @@ -21,15 +22,15 @@ module AbstractController )] def template - render :template => "template" + render template: "template" end def file - render :file => "some/file" + render file: "some/file" end def inline - render :inline => "With <%= :Inline %>" + render inline: "With <%= :Inline %>" end def text @@ -54,7 +55,6 @@ module AbstractController end class TestRenderer < ActiveSupport::TestCase - def setup @controller = ControllerRenderer.new end diff --git a/actionview/test/actionpack/controller/capture_test.rb b/actionview/test/actionpack/controller/capture_test.rb index 933456ce9d..09309e5b6d 100644 --- a/actionview/test/actionpack/controller/capture_test.rb +++ b/actionview/test/actionpack/controller/capture_test.rb @@ -1,30 +1,32 @@ -require 'abstract_unit' -require 'active_support/logger' +# frozen_string_literal: true + +require "abstract_unit" +require "active_support/logger" class CaptureController < ActionController::Base - self.view_paths = [ File.dirname(__FILE__) + '/../../fixtures/actionpack' ] + self.view_paths = [ File.expand_path("../../fixtures/actionpack", __dir__) ] def self.controller_name; "test"; end def self.controller_path; "test"; end def content_for @title = nil - render :layout => "talk_from_action" + render layout: "talk_from_action" end def content_for_with_parameter @title = nil - render :layout => "talk_from_action" + render layout: "talk_from_action" end def content_for_concatenated @title = nil - render :layout => "talk_from_action" + render layout: "talk_from_action" end def non_erb_block_content_for @title = nil - render :layout => "talk_from_action" + render layout: "talk_from_action" end def proper_block_detection diff --git a/actionview/test/actionpack/controller/layout_test.rb b/actionview/test/actionpack/controller/layout_test.rb index 64bc4c41d6..ff66ff2a1a 100644 --- a/actionview/test/actionpack/controller/layout_test.rb +++ b/actionview/test/actionpack/controller/layout_test.rb @@ -1,15 +1,17 @@ -require 'abstract_unit' -require 'active_support/core_ext/array/extract_options' +# frozen_string_literal: true + +require "abstract_unit" +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 # method has access to the view_paths array when looking for a layout to automatically assign. old_load_paths = ActionController::Base.view_paths -ActionController::Base.view_paths = [ File.dirname(__FILE__) + '/../../fixtures/actionpack/layout_tests/' ] +ActionController::Base.view_paths = [ File.expand_path("../../fixtures/actionpack/layout_tests", __dir__) ] class LayoutTest < ActionController::Base - def self.controller_path; 'views' end - def self._implied_layout_name; to_s.underscore.gsub(/_controller$/, '') ; end + def self.controller_path; "views" end + def self._implied_layout_name; to_s.underscore.gsub(/_controller$/, "") ; end self.view_paths = ActionController::Base.view_paths.dup end @@ -54,13 +56,13 @@ class LayoutAutoDiscoveryTest < ActionController::TestCase def test_application_layout_is_default_when_no_controller_match @controller = ProductController.new get :hello - assert_equal 'layout_test.erb hello.erb', @response.body + assert_equal "layout_test.erb hello.erb", @response.body end def test_controller_name_layout_name_match @controller = ItemController.new get :hello - assert_equal 'item.erb hello.erb', @response.body + assert_equal "item.erb hello.erb", @response.body end def test_third_party_template_library_auto_discovers_layout @@ -68,20 +70,20 @@ class LayoutAutoDiscoveryTest < ActionController::TestCase @controller = ThirdPartyTemplateLibraryController.new get :hello assert_response :success - assert_equal 'layouts/third_party_template_library.mab', @response.body + assert_equal "layouts/third_party_template_library.mab", @response.body end end def test_namespaced_controllers_auto_detect_layouts1 @controller = ControllerNameSpace::NestedController.new get :hello - assert_equal 'controller_name_space/nested.erb hello.erb', @response.body + assert_equal "controller_name_space/nested.erb hello.erb", @response.body end def test_namespaced_controllers_auto_detect_layouts2 @controller = MultipleExtensions.new get :hello - assert_equal 'multiple_extensions.html.erb hello.erb', @response.body.strip + assert_equal "multiple_extensions.html.erb hello.erb", @response.body.strip end end @@ -91,16 +93,16 @@ end class StreamingLayoutController < LayoutTest def render(*args) options = args.extract_options! - super(*args, options.merge(:stream => true)) + super(*args, options.merge(stream: true)) end end class AbsolutePathLayoutController < LayoutTest - layout File.expand_path(File.expand_path(__FILE__) + '/../../../fixtures/actionpack/layout_tests/layouts/layout_test') + layout File.expand_path("../../fixtures/actionpack/layout_tests/layouts/layout_test", __dir__) end class HasOwnLayoutController < LayoutTest - layout 'item' + layout "item" end class HasNilLayoutSymbol < LayoutTest @@ -117,28 +119,28 @@ end class PrependsViewPathController < LayoutTest def hello - prepend_view_path File.dirname(__FILE__) + '/../../fixtures/actionpack/layout_tests/alt/' - render :layout => 'alt' + prepend_view_path File.expand_path("../../fixtures/actionpack/layout_tests/alt", __dir__) + render layout: "alt" end end class OnlyLayoutController < LayoutTest - layout 'item', :only => "hello" + layout "item", only: "hello" end class ExceptLayoutController < LayoutTest - layout 'item', :except => "goodbye" + layout "item", except: "goodbye" end class SetsLayoutInRenderController < LayoutTest def hello - render :layout => 'third_party_template_library' + render layout: "third_party_template_library" end end class RendersNoLayoutController < LayoutTest def hello - render :layout => false + render layout: false end end @@ -149,75 +151,75 @@ class LayoutSetInResponseTest < ActionController::TestCase def test_layout_set_when_using_default_layout @controller = DefaultLayoutController.new get :hello - assert_includes @response.body, 'layout_test.erb' + assert_includes @response.body, "layout_test.erb" end def test_layout_set_when_using_streaming_layout @controller = StreamingLayoutController.new get :hello - assert_includes @response.body, 'layout_test.erb' + assert_includes @response.body, "layout_test.erb" end def test_layout_set_when_set_in_controller @controller = HasOwnLayoutController.new get :hello - assert_includes @response.body, 'item.erb' + 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_includes @response.body, 'layout_test.erb' + 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_includes @response.body, 'layout_test.erb' + assert_includes @response.body, "layout_test.erb" end def test_layout_only_exception_when_included @controller = OnlyLayoutController.new get :hello - assert_includes @response.body, 'item.erb' + assert_includes @response.body, "item.erb" end def test_layout_only_exception_when_excepted @controller = OnlyLayoutController.new get :goodbye - assert_not_includes @response.body, 'item.erb' + assert_not_includes @response.body, "item.erb" end def test_layout_except_exception_when_included @controller = ExceptLayoutController.new get :hello - assert_includes @response.body, 'item.erb' + assert_includes @response.body, "item.erb" end def test_layout_except_exception_when_excepted @controller = ExceptLayoutController.new get :goodbye - assert_not_includes @response.body, '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_includes @response.body, 'layouts/third_party_template_library.mab' + 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_equal 'hello.erb', @response.body + assert_equal "hello.erb", @response.body end def test_layout_is_picked_from_the_controller_instances_view_path @controller = PrependsViewPathController.new get :hello - assert_includes @response.body, 'alt.erb' + assert_includes @response.body, "alt.erb" end def test_absolute_pathed_layout @@ -240,7 +242,7 @@ end class LayoutStatusIsRendered < LayoutTest def hello - render :status => 401 + render status: 401 end end @@ -252,7 +254,7 @@ class LayoutStatusIsRenderedTest < ActionController::TestCase end end -unless RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ +unless Gem.win_platform? class LayoutSymlinkedTest < LayoutTest layout "symlinked/symlinked_layout" end @@ -262,7 +264,7 @@ unless RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ @controller = LayoutSymlinkedTest.new get :hello assert_response 200 - assert_includes @response.body, 'This is my 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 bdb9e0397b..8a9d7982d3 100644 --- a/actionview/test/actionpack/controller/render_test.rb +++ b/actionview/test/actionpack/controller/render_test.rb @@ -1,45 +1,16 @@ -require 'abstract_unit' -require 'active_model' +# frozen_string_literal: true + +require "abstract_unit" +require "active_model" +require "controller/fake_models" class ApplicationController < ActionController::Base self.view_paths = File.join(FIXTURE_LOAD_PATH, "actionpack") end -class Customer < Struct.new(:name, :id) - extend ActiveModel::Naming - include ActiveModel::Conversion - - undef_method :to_json - - def to_xml(options={}) - if options[:builder] - options[:builder].name name - else - "<name>#{name}</name>" - end - end - - def to_js(options={}) - "name: #{name.inspect}" - end - alias :to_text :to_js - - def errors - [] - end - - def persisted? - id.present? - end - - def cache_key - name.to_s - end -end - module Quiz - #Models - class Question < Struct.new(:name, :id) + # Models + Question = Struct.new(:name, :id) do extend ActiveModel::Naming include ActiveModel::Conversion @@ -51,20 +22,17 @@ module Quiz # Controller class QuestionsController < ApplicationController def new - render :partial => Quiz::Question.new("Namespaced Partial") + render partial: Quiz::Question.new("Namespaced Partial") end end end -class BadCustomer < Customer; end -class GoodCustomer < Customer; end - module Fun class GamesController < ApplicationController def hello_world; end def nested_partial_with_form_builder - render :partial => ActionView::Helpers::FormBuilder.new(:post, nil, view_context, {}) + render partial: ActionView::Helpers::FormBuilder.new(:post, nil, view_context, {}) end end end @@ -90,7 +58,7 @@ class TestController < ApplicationController end def hello_world_file - render :file => File.expand_path("../../../fixtures/actionpack/hello", __FILE__), :formats => [:html] + render file: File.expand_path("../../fixtures/actionpack/hello", __dir__), formats: [:html] end # :ported: @@ -110,12 +78,12 @@ class TestController < ApplicationController # :ported: def render_template_in_top_directory - render :template => 'shared' + render template: "shared" end # :deprecated: def render_template_in_top_directory_with_slash - render '/shared' + render "/shared" end # :ported: @@ -126,11 +94,11 @@ class TestController < ApplicationController # :ported: def render_action_hello_world - render :action => "hello_world" + render action: "hello_world" end def render_action_upcased_hello_world - render :action => "Hello_world" + render action: "Hello_world" end def render_action_hello_world_as_string @@ -138,7 +106,7 @@ class TestController < ApplicationController end def render_action_hello_world_with_symbol - render :action => :hello_world + render action: :hello_world end # :ported: @@ -149,70 +117,70 @@ class TestController < ApplicationController # :ported: def render_text_hello_world_with_layout @variable_for_layout = ", I am here!" - render plain: "hello world", :layout => true + render plain: "hello world", layout: true end def hello_world_with_layout_false - render :layout => false + render layout: false end # :ported: def render_file_with_instance_variables - @secret = 'in the sauce' - path = File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_ivar') - render :file => path + @secret = "in the sauce" + path = File.expand_path("../../fixtures/test/render_file_with_ivar", __dir__) + render file: path end # :ported: def render_file_not_using_full_path - @secret = 'in the sauce' - render :file => 'test/render_file_with_ivar' + @secret = "in the sauce" + render file: "test/render_file_with_ivar" end def render_file_not_using_full_path_with_dot_in_path - @secret = 'in the sauce' - render :file => 'test/dot.directory/render_file_with_ivar' + @secret = "in the sauce" + render file: "test/dot.directory/render_file_with_ivar" end def render_file_using_pathname - @secret = 'in the sauce' - render :file => Pathname.new(File.dirname(__FILE__)).join('..', '..', 'fixtures', 'test', 'dot.directory', 'render_file_with_ivar') + @secret = "in the sauce" + render file: Pathname.new(__dir__).join("..", "..", "fixtures", "test", "dot.directory", "render_file_with_ivar") end def render_file_from_template - @secret = 'in the sauce' - @path = File.expand_path(File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_ivar')) + @secret = "in the sauce" + @path = File.expand_path("../../fixtures/test/render_file_with_ivar", __dir__) end def render_file_with_locals - path = File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_locals') - render :file => path, :locals => {:secret => 'in the sauce'} + path = File.expand_path("../../fixtures/test/render_file_with_locals", __dir__) + render file: path, locals: { secret: "in the sauce" } end def render_file_as_string_with_locals - path = File.expand_path(File.join(File.dirname(__FILE__), '../../fixtures/test/render_file_with_locals')) - render file: path, :locals => {:secret => 'in the sauce'} + path = File.expand_path("../../fixtures/test/render_file_with_locals", __dir__) + render file: path, locals: { secret: "in the sauce" } end def accessing_request_in_template - render :inline => "Hello: <%= request.host %>" + render inline: "Hello: <%= request.host %>" end def accessing_logger_in_template - render :inline => "<%= logger.class %>" + render inline: "<%= logger.class %>" end def accessing_action_name_in_template - render :inline => "<%= action_name %>" + render inline: "<%= action_name %>" end def accessing_controller_name_in_template - render :inline => "<%= controller_name %>" + render inline: "<%= controller_name %>" end # :ported: def render_custom_code - render plain: "hello world", :status => 404 + render plain: "hello world", status: 404 end # :ported: @@ -240,7 +208,7 @@ class TestController < ApplicationController # setting content type def render_xml_hello @name = "David" - render :template => "test/hello" + render template: "test/hello" end def render_xml_hello_as_string_template @@ -249,7 +217,7 @@ class TestController < ApplicationController end def render_line_offset - render :inline => '<% raise %>', :locals => {:foo => 'bar'} + render inline: "<% raise %>", locals: { foo: "bar" } end def heading @@ -262,49 +230,49 @@ class TestController < ApplicationController # :ported: def blank_response - render plain: ' ' + render plain: " " end # :ported: def layout_test - render :action => "hello_world" + render action: "hello_world" end # :ported: def builder_layout_test @name = nil - render :action => "hello", :layout => "layouts/builder" + render action: "hello", layout: "layouts/builder" end # :move: test this in Action View def builder_partial_test - render :action => "hello_world_container" + render action: "hello_world_container" end # :ported: def partials_list - @test_unchanged = 'hello' + @test_unchanged = "hello" @customers = [ Customer.new("david"), Customer.new("mary") ] - render :action => "list" + render action: "list" end def partial_only - render :partial => true + render partial: true end def hello_in_a_string @customers = [ Customer.new("david"), Customer.new("mary") ] - render plain: "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 - render :inline => "Hello: <%= params[:name] %>" + render inline: "Hello: <%= params[:name] %>" end def accessing_local_assigns_in_inline_template name = params[:local_name] - render :inline => "<%= 'Goodbye, ' + local_name %>", - :locals => { :local_name => name } + render inline: "<%= 'Goodbye, ' + local_name %>", + locals: { local_name: name } end def render_implicit_html_template_from_xhr_request @@ -320,7 +288,7 @@ class TestController < ApplicationController end def render_to_string_test - @foo = render_to_string :inline => "this is a test" + @foo = render_to_string inline: "this is a test" end def default_render @@ -333,27 +301,27 @@ class TestController < ApplicationController end def render_action_hello_world_as_symbol - render :action => :hello_world + render action: :hello_world end def layout_test_with_different_layout - render :action => "hello_world", :layout => "standard" + render action: "hello_world", layout: "standard" end def layout_test_with_different_layout_and_string_action - render "hello_world", :layout => "standard" + render "hello_world", layout: "standard" end def layout_test_with_different_layout_and_symbol_action - render :hello_world, :layout => "standard" + render :hello_world, layout: "standard" end def rendering_without_layout - render :action => "hello_world", :layout => false + render action: "hello_world", layout: false end def layout_overriding_layout - render :action => "hello_world", :layout => "standard" + render action: "hello_world", layout: "standard" end def rendering_nothing_on_layout @@ -364,38 +332,38 @@ class TestController < ApplicationController @before = "i'm before the render" render_to_string plain: "foo" @after = "i'm after the render" - render :template => "test/hello_world" + render template: "test/hello_world" end def render_to_string_with_exception - render_to_string :file => "exception that will not be caught - this will certainly not work" + render_to_string file: "exception that will not be caught - this will certainly not work" end def render_to_string_with_caught_exception @before = "i'm before the render" begin - render_to_string :file => "exception that will be caught- hope my future instance vars still work!" + render_to_string file: "exception that will be caught- hope my future instance vars still work!" rescue end @after = "i'm after the render" - render :template => "test/hello_world" + render template: "test/hello_world" end def accessing_params_in_template_with_layout - render :layout => true, :inline => "Hello: <%= params[:name] %>" + render layout: true, inline: "Hello: <%= params[:name] %>" end # :ported: def render_with_explicit_template - render :template => "test/hello_world" + render template: "test/hello_world" end def render_with_explicit_unescaped_template - render :template => "test/h*llo_world" + render template: "test/h*llo_world" end def render_with_explicit_escaped_template - render :template => "test/hello,world" + render template: "test/hello,world" end def render_with_explicit_string_template @@ -404,7 +372,7 @@ class TestController < ApplicationController # :ported: def render_with_explicit_template_with_locals - render :template => "test/render_file_with_locals", :locals => { :secret => 'area51' } + render template: "test/render_file_with_locals", locals: { secret: "area51" } end # :ported: @@ -414,13 +382,13 @@ class TestController < ApplicationController end def double_redirect - redirect_to :action => "double_render" - redirect_to :action => "double_render" + redirect_to action: "double_render" + redirect_to action: "double_render" end def render_and_redirect render plain: "hello" - redirect_to :action => "double_render" + redirect_to action: "double_render" end def render_to_string_and_render @@ -429,22 +397,22 @@ class TestController < ApplicationController end def render_to_string_with_inline_and_render - render_to_string :inline => "<%= 'dlrow olleh'.reverse %>" - render :template => "test/hello_world" + render_to_string inline: "<%= 'dlrow olleh'.reverse %>" + render template: "test/hello_world" end def rendering_with_conflicting_local_vars @name = "David" - render :action => "potential_conflicts" + render action: "potential_conflicts" end def hello_world_from_rxml_using_action - render :action => "hello_world_from_rxml", :handlers => [:builder] + render action: "hello_world_from_rxml", handlers: [:builder] end # :deprecated: def hello_world_from_rxml_using_template - render :template => "test/hello_world_from_rxml", :handlers => [:builder] + render template: "test/hello_world_from_rxml", handlers: [:builder] end def action_talk_to_layout @@ -458,11 +426,11 @@ class TestController < ApplicationController end def render_with_assigns_option - render inline: '<%= @hello %>', assigns: { hello: "world" } + render inline: "<%= @hello %>", assigns: { hello: "world" } end def yield_content_for - render :action => "content_for", :layout => "yield" + render action: "content_for", layout: "yield" end def render_content_type_from_body @@ -471,117 +439,117 @@ class TestController < ApplicationController end def render_using_layout_around_block - render :action => "using_layout_around_block" + render action: "using_layout_around_block" end def render_using_layout_around_block_in_main_layout_and_within_content_for_layout - render :action => "using_layout_around_block", :layout => "layouts/block_with_layout" + render action: "using_layout_around_block", layout: "layouts/block_with_layout" end def partial_formats_html - render :partial => 'partial', :formats => [:html] + render partial: "partial", formats: [:html] end def partial - render :partial => 'partial' + render partial: "partial" end def partial_html_erb - render :partial => 'partial_html_erb' + render partial: "partial_html_erb" end def render_to_string_with_partial - @partial_only = render_to_string :partial => "partial_only" - @partial_with_locals = render_to_string :partial => "customer", :locals => { :customer => Customer.new("david") } - render :template => "test/hello_world" + @partial_only = render_to_string partial: "partial_only" + @partial_with_locals = render_to_string partial: "customer", locals: { customer: Customer.new("david") } + render template: "test/hello_world" end def render_to_string_with_template_and_html_partial - @text = render_to_string :template => "test/with_partial", :formats => [:text] - @html = render_to_string :template => "test/with_partial", :formats => [:html] - render :template => "test/with_html_partial" + @text = render_to_string template: "test/with_partial", formats: [:text] + @html = render_to_string template: "test/with_partial", formats: [:html] + render template: "test/with_html_partial" end def render_to_string_and_render_with_different_formats - @html = render_to_string :template => "test/with_partial", :formats => [:html] - render :template => "test/with_partial", :formats => [:text] + @html = render_to_string template: "test/with_partial", formats: [:html] + render template: "test/with_partial", formats: [:text] end def render_template_within_a_template_with_other_format - render :template => "test/with_xml_template", - :formats => [:html], - :layout => "with_html_partial" + render template: "test/with_xml_template", + formats: [:html], + layout: "with_html_partial" end def partial_with_counter - render :partial => "counter", :locals => { :counter_counter => 5 } + render partial: "counter", locals: { counter_counter: 5 } end def partial_with_locals - render :partial => "customer", :locals => { :customer => Customer.new("david") } + render partial: "customer", locals: { customer: Customer.new("david") } end def partial_with_form_builder - render :partial => ActionView::Helpers::FormBuilder.new(:post, nil, view_context, {}) + render partial: ActionView::Helpers::FormBuilder.new(:post, nil, view_context, {}) end def partial_with_form_builder_subclass - render :partial => LabellingFormBuilder.new(:post, nil, view_context, {}) + render partial: LabellingFormBuilder.new(:post, nil, view_context, {}) end def partial_collection - render :partial => "customer", :collection => [ Customer.new("david"), Customer.new("mary") ] + render partial: "customer", collection: [ Customer.new("david"), Customer.new("mary") ] end def partial_collection_with_as - render :partial => "customer_with_var", :collection => [ Customer.new("david"), Customer.new("mary") ], :as => :customer + render partial: "customer_with_var", collection: [ Customer.new("david"), Customer.new("mary") ], as: :customer end def partial_collection_with_iteration - render partial: "customer_iteration", collection: [ Customer.new("david"), Customer.new("mary"), Customer.new('christine') ] + render partial: "customer_iteration", collection: [ Customer.new("david"), Customer.new("mary"), Customer.new("christine") ] end def partial_collection_with_as_and_iteration - render partial: "customer_iteration_with_as", collection: [ Customer.new("david"), Customer.new("mary"), Customer.new('christine') ], as: :client + render partial: "customer_iteration_with_as", collection: [ Customer.new("david"), Customer.new("mary"), Customer.new("christine") ], as: :client end def partial_collection_with_counter - render :partial => "customer_counter", :collection => [ Customer.new("david"), Customer.new("mary") ] + render partial: "customer_counter", collection: [ Customer.new("david"), Customer.new("mary") ] end def partial_collection_with_as_and_counter - render :partial => "customer_counter_with_as", :collection => [ Customer.new("david"), Customer.new("mary") ], :as => :client + render partial: "customer_counter_with_as", collection: [ Customer.new("david"), Customer.new("mary") ], as: :client end def partial_collection_with_locals - render :partial => "customer_greeting", :collection => [ Customer.new("david"), Customer.new("mary") ], :locals => { :greeting => "Bonjour" } + render partial: "customer_greeting", collection: [ Customer.new("david"), Customer.new("mary") ], locals: { greeting: "Bonjour" } end def partial_collection_with_spacer - render :partial => "customer", :spacer_template => "partial_only", :collection => [ Customer.new("david"), Customer.new("mary") ] + render partial: "customer", spacer_template: "partial_only", collection: [ Customer.new("david"), Customer.new("mary") ] end def partial_collection_with_spacer_which_uses_render - render :partial => "customer", :spacer_template => "partial_with_partial", :collection => [ Customer.new("david"), Customer.new("mary") ] + render partial: "customer", spacer_template: "partial_with_partial", collection: [ Customer.new("david"), Customer.new("mary") ] end def partial_collection_shorthand_with_locals - render :partial => [ Customer.new("david"), Customer.new("mary") ], :locals => { :greeting => "Bonjour" } + render partial: [ Customer.new("david"), Customer.new("mary") ], locals: { greeting: "Bonjour" } end def partial_collection_shorthand_with_different_types_of_records - render :partial => [ + render partial: [ BadCustomer.new("mark"), GoodCustomer.new("craig"), BadCustomer.new("john"), GoodCustomer.new("zach"), GoodCustomer.new("brandon"), BadCustomer.new("dan") ], - :locals => { :greeting => "Bonjour" } + locals: { greeting: "Bonjour" } end def empty_partial_collection - render :partial => "customer", :collection => [] + render partial: "customer", collection: [] end def partial_collection_shorthand_with_different_types_of_records_with_counter @@ -589,15 +557,15 @@ class TestController < ApplicationController end def missing_partial - render :partial => 'thisFileIsntHere' + render partial: "thisFileIsntHere" end def partial_with_hash_object - render :partial => "hash_object", :object => {:first_name => "Sam"} + render partial: "hash_object", object: { first_name: "Sam" } end def partial_with_nested_object - render :partial => "quiz/questions/question", :object => Quiz::Question.new("first") + render partial: "quiz/questions/question", object: Quiz::Question.new("first") end def partial_with_nested_object_shorthand @@ -605,24 +573,24 @@ class TestController < ApplicationController end def partial_hash_collection - render :partial => "hash_object", :collection => [ {:first_name => "Pratik"}, {:first_name => "Amy"} ] + render partial: "hash_object", collection: [ { first_name: "Pratik" }, { first_name: "Amy" } ] end def partial_hash_collection_with_locals - render :partial => "hash_greeting", :collection => [ {:first_name => "Pratik"}, {:first_name => "Amy"} ], :locals => { :greeting => "Hola" } + render partial: "hash_greeting", collection: [ { first_name: "Pratik" }, { first_name: "Amy" } ], locals: { greeting: "Hola" } end def partial_with_implicit_local_assignment @customer = Customer.new("Marcel") - render :partial => "customer" + render partial: "customer" end def render_call_to_partial_with_layout - render :action => "calling_partial_with_layout" + render action: "calling_partial_with_layout" end def render_call_to_partial_with_layout_in_main_layout_and_within_content_for_layout - render :action => "calling_partial_with_layout", :layout => "layouts/partial_with_layout" + render action: "calling_partial_with_layout", layout: "layouts/partial_with_layout" end before_action only: :render_with_filters do @@ -631,7 +599,7 @@ class TestController < ApplicationController # Ensure that the before filter is executed *before* self.formats is set. def render_with_filters - render :action => :formatted_xml_erb + render action: :formatted_xml_erb end private @@ -642,7 +610,7 @@ class TestController < ApplicationController def determine_layout case action_name - when "hello_world", "layout_test", "rendering_without_layout", + when "hello_world", "layout_test", "rendering_without_layout", "rendering_nothing_on_layout", "render_text_hello_world", "render_text_hello_world_with_layout", "hello_world_with_layout_false", @@ -652,11 +620,11 @@ class TestController < ApplicationController "render_with_explicit_string_template", "update_page", "update_page_with_instance_variables" - "layouts/standard" - when "action_talk_to_layout", "layout_overriding_layout" - "layouts/talk_from_action" - when "render_implicit_html_template_from_xhr_request" - (request.xhr? ? 'layouts/xhr' : 'layouts/standard') + "layouts/standard" + when "action_talk_to_layout", "layout_overriding_layout" + "layouts/talk_from_action" + when "render_implicit_html_template_from_xhr_request" + (request.xhr? ? "layouts/xhr" : "layouts/standard") end end end @@ -726,11 +694,6 @@ class RenderTest < ActionController::TestCase assert_equal "Elastica", @response.body end - def test_render_process - get :render_action_hello_world_as_string - assert_equal "Hello world!", @controller.process(:render_action_hello_world_as_string) - end - # :ported: def test_render_from_variable get :render_hello_world_from_variable @@ -776,7 +739,7 @@ class RenderTest < ActionController::TestCase # :ported: def test_do_with_render_action_and_layout_false get :hello_world_with_layout_false - assert_equal 'Hello world!', @response.body + assert_equal "Hello world!", @response.body end # :ported: @@ -831,27 +794,27 @@ class RenderTest < ActionController::TestCase get :render_custom_code assert_response 404 assert_response :missing - assert_equal 'hello world', @response.body + assert_equal "hello world", @response.body end # :ported: def test_render_text_with_nil get :render_text_with_nil assert_response 200 - assert_equal '', @response.body + assert_equal "", @response.body end # :ported: def test_render_text_with_false get :render_text_with_false - assert_equal 'false', @response.body + assert_equal "false", @response.body end # :ported: def test_render_nothing_with_appendix get :render_nothing_with_appendix assert_response 200 - assert_equal 'appended', @response.body + assert_equal "appended", @response.body end def test_render_text_with_resource @@ -946,7 +909,7 @@ class RenderTest < ActionController::TestCase def test_render_to_string_inline get :render_to_string_with_inline_and_render - assert_equal 'Hello world!', @response.body + assert_equal "Hello world!", @response.body end # :ported: @@ -979,24 +942,24 @@ class RenderTest < ActionController::TestCase def test_should_render_formatted_template get :formatted_html_erb - assert_equal 'formatted html erb', @response.body + assert_equal "formatted html erb", @response.body end def test_should_render_formatted_html_erb_template get :formatted_xml_erb - assert_equal '<test>passed formatted html erb</test>', @response.body + assert_equal "<test>passed formatted html erb</test>", @response.body end def test_should_render_formatted_html_erb_template_with_bad_accepts_header @request.env["HTTP_ACCEPT"] = "; a=dsf" get :formatted_xml_erb - assert_equal '<test>passed formatted html erb</test>', @response.body + assert_equal "<test>passed formatted html erb</test>", @response.body end def test_should_render_formatted_html_erb_template_with_faulty_accepts_header @request.accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, */*" get :formatted_xml_erb - assert_equal '<test>passed formatted html erb</test>', @response.body + assert_equal "<test>passed formatted html erb</test>", @response.body end def test_layout_test_with_different_layout @@ -1026,7 +989,7 @@ class RenderTest < ActionController::TestCase def test_rendering_nothing_on_layout get :rendering_nothing_on_layout - assert_equal '', @response.body + assert_equal "", @response.body end def test_render_to_string_doesnt_break_assigns @@ -1108,7 +1071,7 @@ class RenderTest < ActionController::TestCase def test_render_text_with_assigns_option get :render_with_assigns_option - assert_equal 'world', response.body + assert_equal "world", response.body end # :ported: diff --git a/actionview/test/actionpack/controller/view_paths_test.rb b/actionview/test/actionpack/controller/view_paths_test.rb index e99659c802..45c662f0ce 100644 --- a/actionview/test/actionpack/controller/view_paths_test.rb +++ b/actionview/test/actionpack/controller/view_paths_test.rb @@ -1,4 +1,6 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class ViewLoadPathsTest < ActionController::TestCase class TestController < ActionController::Base @@ -7,7 +9,7 @@ class ViewLoadPathsTest < ActionController::TestCase before_action :add_view_path, only: :hello_world_at_request_time def hello_world() end - def hello_world_at_request_time() render(:action => 'hello_world') end + def hello_world_at_request_time() render(action: "hello_world") end private def add_view_path @@ -17,15 +19,15 @@ class ViewLoadPathsTest < ActionController::TestCase module Test class SubController < ActionController::Base - layout 'test/sub' - def hello_world; render(:template => 'test/hello_world'); end + layout "test/sub" + def hello_world; render(template: "test/hello_world"); end end end def setup - @request = ActionController::TestRequest.create - @response = ActionDispatch::TestResponse.new @controller = TestController.new + @request = ActionController::TestRequest.create(@controller.class) + @response = ActionDispatch::TestResponse.new @paths = TestController.view_paths end @@ -34,7 +36,7 @@ class ViewLoadPathsTest < ActionController::TestCase end def expand(array) - array.map {|x| File.expand_path(x.to_s)} + array.map { |x| File.expand_path(x.to_s) } end def assert_paths(*paths) @@ -47,7 +49,7 @@ class ViewLoadPathsTest < ActionController::TestCase end def test_controller_appends_view_path_correctly - @controller.append_view_path 'foo' + @controller.append_view_path "foo" assert_paths(FIXTURE_LOAD_PATH, "foo") @controller.append_view_path(%w(bar baz)) @@ -58,7 +60,7 @@ class ViewLoadPathsTest < ActionController::TestCase end def test_controller_prepends_view_path_correctly - @controller.prepend_view_path 'baz' + @controller.prepend_view_path "baz" assert_paths("baz", FIXTURE_LOAD_PATH) @controller.prepend_view_path(%w(foo bar)) @@ -72,7 +74,7 @@ class ViewLoadPathsTest < ActionController::TestCase @controller.instance_variable_set :@template, ActionView::Base.new(TestController.view_paths, {}, @controller) class_view_paths = TestController.view_paths - @controller.append_view_path 'foo' + @controller.append_view_path "foo" assert_paths FIXTURE_LOAD_PATH, "foo" @controller.append_view_path(%w(bar baz)) @@ -84,7 +86,7 @@ class ViewLoadPathsTest < ActionController::TestCase @controller.instance_variable_set :@template, ActionView::Base.new(TestController.view_paths, {}, @controller) class_view_paths = TestController.view_paths - @controller.prepend_view_path 'baz' + @controller.prepend_view_path "baz" assert_paths "baz", FIXTURE_LOAD_PATH @controller.prepend_view_path(%w(foo bar)) @@ -131,10 +133,8 @@ class ViewLoadPathsTest < ActionController::TestCase "Decorated body", template.identifier, template.handler, - { - :virtual_path => template.virtual_path, - :format => template.formats - } + virtual_path: template.virtual_path, + format: template.formats ) end end @@ -157,14 +157,14 @@ class ViewLoadPathsTest < ActionController::TestCase class C < ActionController::Base; end } - A.view_paths = ['a/path'] + A.view_paths = ["a/path"] assert_paths A, "a/path" assert_paths A, *B.view_paths assert_paths C, *original_load_paths C.view_paths = [] - assert_nothing_raised { C.append_view_path 'c/path' } + assert_nothing_raised { C.append_view_path "c/path" } assert_paths C, "c/path" end diff --git a/actionview/test/active_record_unit.rb b/actionview/test/active_record_unit.rb index f9e94413b5..7f48b515a0 100644 --- a/actionview/test/active_record_unit.rb +++ b/actionview/test/active_record_unit.rb @@ -1,4 +1,6 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" # Define the essentials class ActiveRecordTestConnector @@ -13,10 +15,10 @@ end # Try to grab AR unless defined?(ActiveRecord) && defined?(FixtureSet) begin - PATH_TO_AR = "#{File.dirname(__FILE__)}/../../activerecord/lib" + PATH_TO_AR = File.expand_path("../../activerecord/lib", __dir__) raise LoadError, "#{PATH_TO_AR} doesn't exist" unless File.directory?(PATH_TO_AR) $LOAD_PATH.unshift PATH_TO_AR - require 'active_record' + require "active_record" rescue LoadError => e $stderr.print "Failed to load Active Record. Skipping Active Record assertion tests: #{e}" ActiveRecordTestConnector.able_to_connect = false @@ -24,12 +26,11 @@ unless defined?(ActiveRecord) && defined?(FixtureSet) end $stderr.flush - # Define the rest of the connector class ActiveRecordTestConnector class << self def setup - unless self.connected || !self.able_to_connect + unless connected || !able_to_connect setup_connection load_schema require_fixture_models @@ -37,21 +38,21 @@ class ActiveRecordTestConnector end rescue Exception => e # errors from ActiveRecord setup $stderr.puts "\nSkipping ActiveRecord assertion tests: #{e}" - #$stderr.puts " #{e.backtrace.join("\n ")}\n" + # $stderr.puts " #{e.backtrace.join("\n ")}\n" self.able_to_connect = false end private def setup_connection if Object.const_defined?(:ActiveRecord) - defaults = { :database => ':memory:' } - adapter = defined?(JRUBY_VERSION) ? 'jdbcsqlite3' : 'sqlite3' - options = defaults.merge :adapter => adapter, :timeout => 500 + defaults = { database: ":memory:" } + adapter = defined?(JRUBY_VERSION) ? "jdbcsqlite3" : "sqlite3" + options = defaults.merge adapter: adapter, timeout: 500 ActiveRecord::Base.establish_connection(options) - ActiveRecord::Base.configurations = { 'sqlite3_ar_integration' => options } + ActiveRecord::Base.configurations = { "sqlite3_ar_integration" => options } ActiveRecord::Base.connection - Object.send(:const_set, :QUOTED_TYPE, ActiveRecord::Base.connection.quote_column_name('type')) unless Object.const_defined?(:QUOTED_TYPE) + Object.send(:const_set, :QUOTED_TYPE, ActiveRecord::Base.connection.quote_column_name("type")) unless Object.const_defined?(:QUOTED_TYPE) else raise "Can't setup connection since ActiveRecord isn't loaded." end @@ -59,13 +60,13 @@ class ActiveRecordTestConnector # Load actionpack sqlite3 tables def load_schema - File.read(File.dirname(__FILE__) + "/fixtures/db_definitions/sqlite.sql").split(';').each do |sql| + File.read(File.expand_path("fixtures/db_definitions/sqlite.sql", __dir__)).split(";").each do |sql| ActiveRecord::Base.connection.execute(sql) unless sql.blank? end end def require_fixture_models - Dir.glob(File.dirname(__FILE__) + "/fixtures/*.rb").each {|f| require f} + Dir.glob(File.expand_path("fixtures/*.rb", __dir__)).each { |f| require f } end end end diff --git a/actionview/test/activerecord/controller_runtime_test.rb b/actionview/test/activerecord/controller_runtime_test.rb index af91348d76..42b171ea07 100644 --- a/actionview/test/activerecord/controller_runtime_test.rb +++ b/actionview/test/activerecord/controller_runtime_test.rb @@ -1,19 +1,21 @@ -require 'active_record_unit' -require 'active_record/railties/controller_runtime' -require 'fixtures/project' -require 'active_support/log_subscriber/test_helper' -require 'action_controller/log_subscriber' +# frozen_string_literal: true + +require "active_record_unit" +require "active_record/railties/controller_runtime" +require "fixtures/project" +require "active_support/log_subscriber/test_helper" +require "action_controller/log_subscriber" ActionController::Base.include(ActiveRecord::Railties::ControllerRuntime) class ControllerRuntimeLogSubscriberTest < ActionController::TestCase class LogSubscriberController < ActionController::Base def show - render :inline => "<%= Project.all %>" + render inline: "<%= Project.all %>" end def zero - render :inline => "Zero DB runtime" + render inline: "Zero DB runtime" end def create @@ -24,11 +26,11 @@ class ControllerRuntimeLogSubscriberTest < ActionController::TestCase def redirect Project.all - redirect_to :action => 'show' + redirect_to action: "show" end def db_after_render - render :inline => "Hello world" + render inline: "Hello world" Project.all ActiveRecord::LogSubscriber.runtime += 100 end @@ -38,8 +40,8 @@ class ControllerRuntimeLogSubscriberTest < ActionController::TestCase tests LogSubscriberController def setup - super @old_logger = ActionController::Base.logger + super ActionController::LogSubscriber.attach_to :action_controller end @@ -67,7 +69,7 @@ class ControllerRuntimeLogSubscriberTest < ActionController::TestCase wait assert_equal 2, @logger.logged(:info).size - assert_match(/\(Views: [\d.]+ms \| ActiveRecord: 0.0ms\)/, @logger.logged(:info)[1]) + assert_match(/\(Views: [\d.]+ms \| ActiveRecord: 0\.0ms\)/, @logger.logged(:info)[1]) end def test_log_with_active_record_when_post diff --git a/actionview/test/activerecord/debug_helper_test.rb b/actionview/test/activerecord/debug_helper_test.rb index 03cb1d5a91..4be1023733 100644 --- a/actionview/test/activerecord/debug_helper_test.rb +++ b/actionview/test/activerecord/debug_helper_test.rb @@ -1,14 +1,19 @@ -require 'active_record_unit' -require 'nokogiri' +# frozen_string_literal: true + +require "active_record_unit" +require "nokogiri" class DebugHelperTest < ActionView::TestCase def test_debug company = Company.new(name: "firebase") - assert_match "name: firebase", debug(company) + output = debug(company) + assert_match "name: name", output + assert_match "value_before_type_cast: firebase", output + assert_match "active_record_yaml_version: 2", output end def test_debug_with_marshal_error - obj = -> { } + 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 2769b97445..1472ee8def 100644 --- a/actionview/test/activerecord/form_helper_activerecord_test.rb +++ b/actionview/test/activerecord/form_helper_activerecord_test.rb @@ -1,6 +1,8 @@ -require 'active_record_unit' -require 'fixtures/project' -require 'fixtures/developer' +# frozen_string_literal: true + +require "active_record_unit" +require "fixtures/project" +require "fixtures/developer" class FormHelperActiveRecordTest < ActionView::TestCase tests ActionView::Helpers::FormHelper @@ -39,50 +41,50 @@ class FormHelperActiveRecordTest < ActionView::TestCase def test_nested_fields_for_with_child_index_option_override_on_a_nested_attributes_collection_association form_for(@developer) do |f| - concat f.fields_for(:projects, @developer.projects.first, :child_index => 'abc') { |cf| + concat f.fields_for(:projects, @developer.projects.first, child_index: "abc") { |cf| concat cf.text_field(:name) } end - expected = whole_form('/developers/123', 'edit_developer_123', 'edit_developer', :method => 'patch') do - '<input id="developer_projects_attributes_abc_name" name="developer[projects_attributes][abc][name]" type="text" value="project #321" />' + + expected = whole_form("/developers/123", "edit_developer_123", "edit_developer", method: "patch") do + '<input id="developer_projects_attributes_abc_name" name="developer[projects_attributes][abc][name]" type="text" value="project #321" />' \ '<input id="developer_projects_attributes_abc_id" name="developer[projects_attributes][abc][id]" type="hidden" value="321" />' end assert_dom_equal expected, output_buffer end - protected + private + + def hidden_fields(method = nil) + txt = %{<input name="utf8" type="hidden" value="✓" />}.dup - def hidden_fields(method = nil) - txt = %{<input name="utf8" type="hidden" value="✓" />} + if method && !%w(get post).include?(method.to_s) + txt << %{<input name="_method" type="hidden" value="#{method}" />} + end - if method && !%w(get post).include?(method.to_s) - txt << %{<input name="_method" type="hidden" value="#{method}" />} + txt end - txt - end + def form_text(action = "/", id = nil, html_class = nil, remote = nil, multipart = nil, method = nil) + txt = %{<form accept-charset="UTF-8" action="#{action}"}.dup + txt << %{ enctype="multipart/form-data"} if multipart + txt << %{ data-remote="true"} if remote + txt << %{ class="#{html_class}"} if html_class + txt << %{ id="#{id}"} if id + method = method.to_s == "get" ? "get" : "post" + txt << %{ method="#{method}">} + end - def form_text(action = "/", id = nil, html_class = nil, remote = nil, multipart = nil, method = nil) - txt = %{<form accept-charset="UTF-8" action="#{action}"} - txt << %{ enctype="multipart/form-data"} if multipart - txt << %{ data-remote="true"} if remote - txt << %{ class="#{html_class}"} if html_class - txt << %{ id="#{id}"} if id - method = method.to_s == "get" ? "get" : "post" - txt << %{ method="#{method}">} - end + def whole_form(action = "/", id = nil, html_class = nil, options = nil) + contents = block_given? ? yield : "" - def whole_form(action = "/", id = nil, html_class = nil, options = nil) - contents = block_given? ? yield : "" + if options.is_a?(Hash) + method, remote, multipart = options.values_at(:method, :remote, :multipart) + else + method = options + end - if options.is_a?(Hash) - method, remote, multipart = options.values_at(:method, :remote, :multipart) - else - method = options + form_text(action, id, html_class, remote, multipart, method) + hidden_fields(method) + contents + "</form>" end - - form_text(action, id, html_class, remote, multipart, method) + hidden_fields(method) + contents + "</form>" - end end diff --git a/actionview/test/activerecord/polymorphic_routes_test.rb b/actionview/test/activerecord/polymorphic_routes_test.rb index 34b2698c7f..4b931f793f 100644 --- a/actionview/test/activerecord/polymorphic_routes_test.rb +++ b/actionview/test/activerecord/polymorphic_routes_test.rb @@ -1,28 +1,30 @@ -require 'active_record_unit' -require 'fixtures/project' +# frozen_string_literal: true + +require "active_record_unit" +require "fixtures/project" class Task < ActiveRecord::Base - self.table_name = 'projects' + self.table_name = "projects" end class Step < ActiveRecord::Base - self.table_name = 'projects' + self.table_name = "projects" end class Bid < ActiveRecord::Base - self.table_name = 'projects' + self.table_name = "projects" end class Tax < ActiveRecord::Base - self.table_name = 'projects' + self.table_name = "projects" end class Fax < ActiveRecord::Base - self.table_name = 'projects' + self.table_name = "projects" end class Series < ActiveRecord::Base - self.table_name = 'projects' + self.table_name = "projects" end class ModelDelegator @@ -41,17 +43,17 @@ class ModelDelegate end def to_param - 'overridden' + "overridden" end end -module Blog +module Weblog class Post < ActiveRecord::Base - self.table_name = 'projects' + self.table_name = "projects" end class Blog < ActiveRecord::Base - self.table_name = 'projects' + self.table_name = "projects" end def self.use_relative_model_naming? @@ -61,7 +63,7 @@ end class PolymorphicRoutesTest < ActionController::TestCase include SharedTestRoutes.url_helpers - self.default_url_options[:host] = 'example.com' + default_url_options[:host] = "example.com" def setup @project = Project.new @@ -72,22 +74,21 @@ class PolymorphicRoutesTest < ActionController::TestCase @fax = Fax.new @delegator = ModelDelegator.new @series = Series.new - @blog_post = Blog::Post.new - @blog_blog = Blog::Blog.new + @blog_post = Weblog::Post.new + @blog_blog = Weblog::Blog.new end def assert_url(url, args) host = self.class.default_url_options[:host] - assert_equal url.sub(/http:\/\/#{host}/, ''), polymorphic_path(args) + assert_equal url.sub(/http:\/\/#{host}/, ""), polymorphic_path(args) assert_equal url, polymorphic_url(args) assert_equal url, url_for(args) end def test_string with_test_routes do - # FIXME: why are these different? Symbol case passes through to - # `polymorphic_url`, but the String case doesn't. + assert_equal "/projects", polymorphic_path("projects") assert_equal "http://example.com/projects", polymorphic_url("projects") assert_equal "projects", url_for("projects") end @@ -95,7 +96,7 @@ class PolymorphicRoutesTest < ActionController::TestCase def test_string_with_options with_test_routes do - assert_equal "http://example.com/projects?id=10", polymorphic_url("projects", :id => 10) + assert_equal "http://example.com/projects?id=10", polymorphic_url("projects", id: 10) end end @@ -107,7 +108,7 @@ class PolymorphicRoutesTest < ActionController::TestCase def test_symbol_with_options with_test_routes do - assert_equal "http://example.com/projects?id=10", polymorphic_url(:projects, :id => 10) + assert_equal "http://example.com/projects?id=10", polymorphic_url(:projects, id: 10) end end @@ -179,7 +180,7 @@ class PolymorphicRoutesTest < ActionController::TestCase def test_with_nil_id with_test_routes do exception = assert_raise ArgumentError do - polymorphic_url({ :id => nil }) + polymorphic_url(id: nil) end assert_equal "Nil location provided. Can't build URI.", exception.message end @@ -233,8 +234,8 @@ class PolymorphicRoutesTest < ActionController::TestCase def test_class_with_options with_test_routes do - assert_equal "http://example.com/projects?foo=bar", polymorphic_url(@project.class, { :foo => :bar }) - assert_equal "/projects?foo=bar", polymorphic_path(@project.class, { :foo => :bar }) + assert_equal "http://example.com/projects?foo=bar", polymorphic_url(@project.class, foo: :bar) + assert_equal "/projects?foo=bar", polymorphic_path(@project.class, foo: :bar) end end @@ -274,7 +275,7 @@ class PolymorphicRoutesTest < ActionController::TestCase def test_with_record_and_action with_test_routes do - assert_equal "http://example.com/projects/new", polymorphic_url(@project, :action => 'new') + assert_equal "http://example.com/projects/new", polymorphic_url(@project, action: "new") end end @@ -303,35 +304,35 @@ class PolymorphicRoutesTest < ActionController::TestCase def test_url_helper_prefixed_with_edit_with_url_options with_test_routes do @project.save - assert_equal "http://example.com/projects/#{@project.id}/edit?param1=10", edit_polymorphic_url(@project, :param1 => '10') + assert_equal "http://example.com/projects/#{@project.id}/edit?param1=10", edit_polymorphic_url(@project, param1: "10") end end def test_url_helper_with_url_options with_test_routes do @project.save - assert_equal "http://example.com/projects/#{@project.id}?param1=10", polymorphic_url(@project, :param1 => '10') + assert_equal "http://example.com/projects/#{@project.id}?param1=10", polymorphic_url(@project, param1: "10") end end def test_format_option with_test_routes do @project.save - assert_equal "http://example.com/projects/#{@project.id}.pdf", polymorphic_url(@project, :format => :pdf) + assert_equal "http://example.com/projects/#{@project.id}.pdf", polymorphic_url(@project, format: :pdf) end end def test_format_option_with_url_options with_test_routes do @project.save - assert_equal "http://example.com/projects/#{@project.id}.pdf?param1=10", polymorphic_url(@project, :format => :pdf, :param1 => '10') + assert_equal "http://example.com/projects/#{@project.id}.pdf?param1=10", polymorphic_url(@project, format: :pdf, param1: "10") end end def test_id_and_format_option with_test_routes do @project.save - assert_equal "http://example.com/projects/#{@project.id}.pdf", polymorphic_url(:id => @project, :format => :pdf) + assert_equal "http://example.com/projects/#{@project.id}.pdf", polymorphic_url(id: @project, format: :pdf) end end @@ -373,7 +374,7 @@ class PolymorphicRoutesTest < ActionController::TestCase def test_new_with_array_and_namespace with_admin_test_routes do - assert_equal "http://example.com/admin/projects/new", polymorphic_url([:admin, @project], :action => 'new') + assert_equal "http://example.com/admin/projects/new", polymorphic_url([:admin, @project], action: "new") end end @@ -426,7 +427,7 @@ class PolymorphicRoutesTest < ActionController::TestCase with_test_routes do @project.save @task.save - assert_equal "http://example.com/projects/#{@project.id}/bid/tasks/#{@task.id}.pdf", polymorphic_url([@project, :bid, @task], :format => :pdf) + assert_equal "http://example.com/projects/#{@project.id}/bid/tasks/#{@task.id}.pdf", polymorphic_url([@project, :bid, @task], format: :pdf) end end @@ -474,13 +475,13 @@ class PolymorphicRoutesTest < ActionController::TestCase def test_with_hash with_test_routes do @project.save - assert_equal "http://example.com/projects/#{@project.id}", polymorphic_url(:id => @project) + assert_equal "http://example.com/projects/#{@project.id}", polymorphic_url(id: @project) end end def test_polymorphic_path_accepts_options with_test_routes do - assert_equal "/projects/new", polymorphic_path(@project, :action => 'new') + assert_equal "/projects/new", polymorphic_path(@project, action: "new") end end @@ -493,7 +494,7 @@ class PolymorphicRoutesTest < ActionController::TestCase object_array = [:admin, @project, @task] original_args = [object_array.dup, options.dup] - assert_no_difference('object_array.size') { polymorphic_path(object_array, options) } + assert_no_difference("object_array.size") { polymorphic_path(object_array, options) } assert_equal original_args, [object_array, options] end end @@ -527,7 +528,7 @@ class PolymorphicRoutesTest < ActionController::TestCase def test_with_irregular_plural_record_and_action with_test_routes do - assert_equal "http://example.com/taxes/new", polymorphic_url(@tax, :action => 'new') + assert_equal "http://example.com/taxes/new", polymorphic_url(@tax, action: "new") end end @@ -561,7 +562,7 @@ class PolymorphicRoutesTest < ActionController::TestCase def test_new_with_irregular_plural_array_and_namespace with_admin_test_routes do - assert_equal "http://example.com/admin/taxes/new", polymorphic_url([:admin, @tax], :action => 'new') + assert_equal "http://example.com/admin/taxes/new", polymorphic_url([:admin, @tax], action: "new") end end @@ -598,7 +599,7 @@ class PolymorphicRoutesTest < ActionController::TestCase end end - # Tests for uncountable names + # Tests for uncountable names def test_uncountable_resource with_test_routes do @series.save @@ -622,7 +623,7 @@ class PolymorphicRoutesTest < ActionController::TestCase def with_namespaced_routes(name) with_routing do |set| set.draw do - scope(:module => name) do + scope(module: name) do resources :blogs do resources :posts do resources :faxes @@ -728,6 +729,52 @@ class PolymorphicPathRoutesTest < PolymorphicRoutesTest def assert_url(url, args) host = self.class.default_url_options[:host] - assert_equal url.sub(/http:\/\/#{host}/, ''), url_for(args) + assert_equal url.sub(/http:\/\/#{host}/, ""), url_for(args) + end +end + +class DirectRoutesTest < ActionView::TestCase + class Linkable + attr_reader :id + + def self.name + super.demodulize + end + + def initialize(id) + @id = id + end + + def linkable_type + self.class.name.underscore + end + end + + class Category < Linkable; end + class Collection < Linkable; end + class Product < Linkable; end + + Routes = ActionDispatch::Routing::RouteSet.new + Routes.draw do + resources :categories, :collections, :products + direct(:linkable) { |linkable| [:"#{linkable.linkable_type}", { id: linkable.id }] } + end + + include Routes.url_helpers + + def setup + @category = Category.new("1") + @collection = Collection.new("2") + @product = Product.new("3") + end + + def test_direct_routes + assert_equal "/categories/1", linkable_path(@category) + assert_equal "/collections/2", linkable_path(@collection) + assert_equal "/products/3", linkable_path(@product) + + assert_equal "http://test.host/categories/1", linkable_url(@category) + assert_equal "http://test.host/collections/2", linkable_url(@collection) + assert_equal "http://test.host/products/3", linkable_url(@product) end end diff --git a/actionview/test/activerecord/relation_cache_test.rb b/actionview/test/activerecord/relation_cache_test.rb index 8e97417b94..bd0cd10eaf 100644 --- a/actionview/test/activerecord/relation_cache_test.rb +++ b/actionview/test/activerecord/relation_cache_test.rb @@ -1,18 +1,23 @@ -require 'active_record_unit' +# frozen_string_literal: true -class RelationCacheTest < ActionView::TestCase +require "active_record_unit" + +class RelationCacheTest < ActionView::TestCase tests ActionView::Helpers::CacheHelper def setup - @virtual_path = "path" + view_paths = ActionController::Base.view_paths + lookup_context = ActionView::LookupContext.new(view_paths, {}, ["test"]) + @view_renderer = ActionView::Renderer.new(lookup_context) + @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}/") + cache(Project.all) { concat("Hello World") } + assert_equal "Hello World", controller.cache_store.read("views/path/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 9772ebb39e..3a698fa42e 100644 --- a/actionview/test/activerecord/render_partial_with_record_identification_test.rb +++ b/actionview/test/activerecord/render_partial_with_record_identification_test.rb @@ -1,48 +1,40 @@ -require 'active_record_unit' +# frozen_string_literal: true + +require "active_record_unit" class RenderPartialWithRecordIdentificationController < ActionController::Base def render_with_has_many_and_belongs_to_association @developer = Developer.find(1) - render :partial => @developer.projects + render partial: @developer.projects end def render_with_has_many_association @topic = Topic.find(1) - render :partial => @topic.replies + render partial: @topic.replies end def render_with_scope - render :partial => Reply.base - end - - def render_with_has_many_through_association - @developer = Developer.first - render :partial => @developer.topics + render partial: Reply.base end def render_with_has_one_association @company = Company.find(1) - render :partial => @company.mascot - end - - def render_with_belongs_to_association - @reply = Reply.find(1) - render :partial => @reply.topic + render partial: @company.mascot end def render_with_record @developer = Developer.first - render :partial => @developer + render partial: @developer end def render_with_record_collection @developers = Developer.all - render :partial => @developers + render partial: @developers end def render_with_record_collection_and_spacer_template @developer = Developer.find(1) - render :partial => @developer.projects, :spacer_template => 'test/partial_only' + render partial: @developer.projects, spacer_template: "test/partial_only" end end @@ -57,27 +49,27 @@ class RenderPartialWithRecordIdentificationTest < ActiveRecordTestCase def test_rendering_partial_with_has_many_association get :render_with_has_many_association - assert_equal 'Birdman is better!', @response.body + assert_equal "Birdman is better!", @response.body end def test_rendering_partial_with_scope get :render_with_scope - assert_equal 'Birdman is better!Nuh uh!', @response.body + assert_equal "Birdman is better!Nuh uh!", @response.body end def test_render_with_record get :render_with_record - assert_equal 'David', @response.body + assert_equal "David", @response.body end def test_render_with_record_collection get :render_with_record_collection - assert_equal 'DavidJamisfixture_3fixture_4fixture_5fixture_6fixture_7fixture_8fixture_9fixture_10Jamis', @response.body + 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 Developer.find(1).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 @@ -87,7 +79,7 @@ class RenderPartialWithRecordIdentificationTest < ActiveRecordTestCase end end -class Game < Struct.new(:name, :id) +Game = Struct.new(:name, :id) do extend ActiveModel::Naming include ActiveModel::Conversion def to_param @@ -98,22 +90,22 @@ end module Fun class NestedController < ActionController::Base def render_with_record_in_nested_controller - render :partial => Game.new("Pong") + render partial: Game.new("Pong") end def render_with_record_collection_in_nested_controller - render :partial => [ Game.new("Pong"), Game.new("Tank") ] + render partial: [ Game.new("Pong"), Game.new("Tank") ] end end module Serious class NestedDeeperController < ActionController::Base def render_with_record_in_deeper_nested_controller - render :partial => Game.new("Chess") + render partial: Game.new("Chess") end def render_with_record_collection_in_deeper_nested_controller - render :partial => [ Game.new("Chess"), Game.new("Sudoku"), Game.new("Solitaire") ] + render partial: [ Game.new("Chess"), Game.new("Sudoku"), Game.new("Solitaire") ] end end end diff --git a/actionview/test/fixtures/actionpack/layouts/builder.builder b/actionview/test/fixtures/actionpack/layouts/builder.builder index 7c7d4b2dd1..c55488edd0 100644 --- a/actionview/test/fixtures/actionpack/layouts/builder.builder +++ b/actionview/test/fixtures/actionpack/layouts/builder.builder @@ -1,3 +1,3 @@ xml.wrapper do xml << yield -end
\ No newline at end of file +end diff --git a/actionview/test/fixtures/actionpack/test/_hello.builder b/actionview/test/fixtures/actionpack/test/_hello.builder index ef52f632d1..fc72df16d0 100644 --- a/actionview/test/fixtures/actionpack/test/_hello.builder +++ b/actionview/test/fixtures/actionpack/test/_hello.builder @@ -1 +1 @@ -xm.hello
\ No newline at end of file +xm.hello diff --git a/actionview/test/fixtures/actionpack/test/formatted_xml_erb.builder b/actionview/test/fixtures/actionpack/test/formatted_xml_erb.builder index 14fd3549fb..f98aaa34a5 100644 --- a/actionview/test/fixtures/actionpack/test/formatted_xml_erb.builder +++ b/actionview/test/fixtures/actionpack/test/formatted_xml_erb.builder @@ -1 +1 @@ -xml.test 'failed'
\ No newline at end of file +xml.test "failed" diff --git a/actionview/test/fixtures/actionpack/test/hello.builder b/actionview/test/fixtures/actionpack/test/hello.builder index a471553941..b8ab17ad5b 100644 --- a/actionview/test/fixtures/actionpack/test/hello.builder +++ b/actionview/test/fixtures/actionpack/test/hello.builder @@ -1,4 +1,4 @@ xml.html do xml.p "Hello #{@name}" - xml << render(:file => "test/greeting") -end
\ No newline at end of file + xml << render(file: "test/greeting") +end diff --git a/actionview/test/fixtures/actionpack/test/hello_world_container.builder b/actionview/test/fixtures/actionpack/test/hello_world_container.builder index e48d75c405..24032ab5e0 100644 --- a/actionview/test/fixtures/actionpack/test/hello_world_container.builder +++ b/actionview/test/fixtures/actionpack/test/hello_world_container.builder @@ -1,3 +1,3 @@ xml.test do - render :partial => 'hello', :locals => { :xm => xml } -end
\ No newline at end of file + render partial: "hello", locals: { xm: xml } +end diff --git a/actionview/test/fixtures/actionpack/test/hello_xml_world.builder b/actionview/test/fixtures/actionpack/test/hello_xml_world.builder index e7081b89fe..d16bb6b5cb 100644 --- a/actionview/test/fixtures/actionpack/test/hello_xml_world.builder +++ b/actionview/test/fixtures/actionpack/test/hello_xml_world.builder @@ -8,4 +8,4 @@ xml.html do xml.p "monks" xml.p "wiseguys" end -end
\ No newline at end of file +end diff --git a/actionview/test/fixtures/actionpack/test/non_erb_block_content_for.builder b/actionview/test/fixtures/actionpack/test/non_erb_block_content_for.builder index d539a425a4..cd65da751b 100644 --- a/actionview/test/fixtures/actionpack/test/non_erb_block_content_for.builder +++ b/actionview/test/fixtures/actionpack/test/non_erb_block_content_for.builder @@ -1,4 +1,4 @@ content_for :title do - 'Putting stuff in the title!' + "Putting stuff in the title!" end xml << "Great stuff!" diff --git a/actionview/test/fixtures/comments/empty.html+grid.erb b/actionview/test/fixtures/comments/empty.html+grid.erb new file mode 100644 index 0000000000..dc3fa32a81 --- /dev/null +++ b/actionview/test/fixtures/comments/empty.html+grid.erb @@ -0,0 +1 @@ +<h1>No Comment</h1> diff --git a/actionview/test/fixtures/comments/empty.html.builder b/actionview/test/fixtures/comments/empty.html.builder index 2b0c7207a3..12d6fdd9a5 100644 --- a/actionview/test/fixtures/comments/empty.html.builder +++ b/actionview/test/fixtures/comments/empty.html.builder @@ -1 +1 @@ -xml.h1 'No Comment'
\ No newline at end of file +xml.h1 "No Comment" diff --git a/actionview/test/fixtures/company.rb b/actionview/test/fixtures/company.rb index f3ac3642fa..93afdd5472 100644 --- a/actionview/test/fixtures/company.rb +++ b/actionview/test/fixtures/company.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + class Company < ActiveRecord::Base has_one :mascot self.sequence_name = :companies_nonstd_seq validates_presence_of :name def validate - errors.add('rating', 'rating should not be 2') if rating == 2 + errors.add("rating", "rating should not be 2") if rating == 2 end end diff --git a/actionview/test/fixtures/developer.rb b/actionview/test/fixtures/developer.rb index 8b3f0a8039..cb7ee49eed 100644 --- a/actionview/test/fixtures/developer.rb +++ b/actionview/test/fixtures/developer.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + class Developer < ActiveRecord::Base has_and_belongs_to_many :projects has_many :replies - has_many :topics, :through => :replies + has_many :topics, through: :replies accepts_nested_attributes_for :projects end diff --git a/actionview/test/fixtures/digestor/api/comments/_comment.json.erb b/actionview/test/fixtures/digestor/api/comments/_comment.json.erb new file mode 100644 index 0000000000..696eb13917 --- /dev/null +++ b/actionview/test/fixtures/digestor/api/comments/_comment.json.erb @@ -0,0 +1 @@ +{"content": "Great story!"} diff --git a/actionview/test/fixtures/digestor/api/comments/_comments.json.erb b/actionview/test/fixtures/digestor/api/comments/_comments.json.erb new file mode 100644 index 0000000000..c28646a283 --- /dev/null +++ b/actionview/test/fixtures/digestor/api/comments/_comments.json.erb @@ -0,0 +1 @@ +<%= render partial: "comments/comment", collection: commentable.comments %> diff --git a/actionview/test/fixtures/digestor/messages/thread.json.erb b/actionview/test/fixtures/digestor/messages/thread.json.erb new file mode 100644 index 0000000000..e4c1ba97cd --- /dev/null +++ b/actionview/test/fixtures/digestor/messages/thread.json.erb @@ -0,0 +1 @@ +<%= render "comments/comments" %> diff --git a/actionview/test/fixtures/helpers/abc_helper.rb b/actionview/test/fixtures/helpers/abc_helper.rb index cf2774bb5f..999b9b5c6e 100644 --- a/actionview/test/fixtures/helpers/abc_helper.rb +++ b/actionview/test/fixtures/helpers/abc_helper.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module AbcHelper def bare_a() end end diff --git a/actionview/test/fixtures/helpers/helpery_test_helper.rb b/actionview/test/fixtures/helpers/helpery_test_helper.rb index a4f2951efa..9836143848 100644 --- a/actionview/test/fixtures/helpers/helpery_test_helper.rb +++ b/actionview/test/fixtures/helpers/helpery_test_helper.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module HelperyTestHelper def helpery_test "Default" diff --git a/actionview/test/fixtures/helpers_missing/invalid_require_helper.rb b/actionview/test/fixtures/helpers_missing/invalid_require_helper.rb index d8801e54d5..c77121046d 100644 --- a/actionview/test/fixtures/helpers_missing/invalid_require_helper.rb +++ b/actionview/test/fixtures/helpers_missing/invalid_require_helper.rb @@ -1,5 +1,6 @@ -require 'very_invalid_file_name' +# frozen_string_literal: true + +require "very_invalid_file_name" module InvalidRequireHelper end - diff --git a/actionview/test/fixtures/layouts/streaming_with_locale.erb b/actionview/test/fixtures/layouts/streaming_with_locale.erb new file mode 100644 index 0000000000..e1fdad2073 --- /dev/null +++ b/actionview/test/fixtures/layouts/streaming_with_locale.erb @@ -0,0 +1,2 @@ +layout.locale: <%= I18n.locale %> +<%= yield %> diff --git a/actionview/test/fixtures/mascot.rb b/actionview/test/fixtures/mascot.rb index f9f1448b8f..26a2c7bbe1 100644 --- a/actionview/test/fixtures/mascot.rb +++ b/actionview/test/fixtures/mascot.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Mascot < ActiveRecord::Base belongs_to :company -end
\ No newline at end of file +end diff --git a/actionview/test/fixtures/project.rb b/actionview/test/fixtures/project.rb index 404b12cbab..019ddb7aef 100644 --- a/actionview/test/fixtures/project.rb +++ b/actionview/test/fixtures/project.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Project < ActiveRecord::Base has_and_belongs_to_many :developers, -> { uniq } diff --git a/actionview/test/fixtures/reply.rb b/actionview/test/fixtures/reply.rb index 047522c55b..b2b662e1b5 100644 --- a/actionview/test/fixtures/reply.rb +++ b/actionview/test/fixtures/reply.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Reply < ActiveRecord::Base scope :base, -> { all } belongs_to :topic, -> { includes(:replies) } diff --git a/actionview/test/fixtures/ruby_template.ruby b/actionview/test/fixtures/ruby_template.ruby index 5097bce47c..93334610a8 100644 --- a/actionview/test/fixtures/ruby_template.ruby +++ b/actionview/test/fixtures/ruby_template.ruby @@ -1,2 +1,2 @@ -body = "" +body = "".dup body << ["Hello", "from", "Ruby", "code"].join(" ") diff --git a/actionview/test/fixtures/test/_builder_tag_nested_in_content_tag.erb b/actionview/test/fixtures/test/_builder_tag_nested_in_content_tag.erb new file mode 100644 index 0000000000..ddad7ec3ac --- /dev/null +++ b/actionview/test/fixtures/test/_builder_tag_nested_in_content_tag.erb @@ -0,0 +1,3 @@ +<%= tag.p do %> + <%= tag.b 'Hello' %> +<% end %> diff --git a/actionview/test/fixtures/test/_cached_nested_cached_customer.erb b/actionview/test/fixtures/test/_cached_nested_cached_customer.erb new file mode 100644 index 0000000000..01bf025cd3 --- /dev/null +++ b/actionview/test/fixtures/test/_cached_nested_cached_customer.erb @@ -0,0 +1,3 @@ +<% cache cached_customer do %> + <%= render partial: "test/cached_customer", locals: { cached_customer: cached_customer } %> +<% end %> diff --git a/actionview/test/fixtures/test/_nested_cached_customer.erb b/actionview/test/fixtures/test/_nested_cached_customer.erb new file mode 100644 index 0000000000..f43adc94c9 --- /dev/null +++ b/actionview/test/fixtures/test/_nested_cached_customer.erb @@ -0,0 +1 @@ +<%= render partial: "test/cached_customer", locals: { cached_customer: cached_customer } %> diff --git a/actionview/test/fixtures/test/_partial_iteration_1.erb b/actionview/test/fixtures/test/_partial_iteration_1.erb new file mode 100644 index 0000000000..c0fdd4c22a --- /dev/null +++ b/actionview/test/fixtures/test/_partial_iteration_1.erb @@ -0,0 +1 @@ +<%= defined?(partial_iteration_1_iteration) %> diff --git a/actionview/test/fixtures/test/_partial_iteration_2.erb b/actionview/test/fixtures/test/_partial_iteration_2.erb new file mode 100644 index 0000000000..50dd11db27 --- /dev/null +++ b/actionview/test/fixtures/test/_partial_iteration_2.erb @@ -0,0 +1 @@ +<%= defined?(partial_iteration_2_iteration) -%> diff --git a/actionview/test/fixtures/test/_partial_with_variants.html+grid.erb b/actionview/test/fixtures/test/_partial_with_variants.html+grid.erb new file mode 100644 index 0000000000..225363c8c3 --- /dev/null +++ b/actionview/test/fixtures/test/_partial_with_variants.html+grid.erb @@ -0,0 +1 @@ +<h1>Partial with variants</h1> diff --git a/actionview/test/fixtures/test/hello.builder b/actionview/test/fixtures/test/hello.builder index a471553941..b8ab17ad5b 100644 --- a/actionview/test/fixtures/test/hello.builder +++ b/actionview/test/fixtures/test/hello.builder @@ -1,4 +1,4 @@ xml.html do xml.p "Hello #{@name}" - xml << render(:file => "test/greeting") -end
\ No newline at end of file + xml << render(file: "test/greeting") +end diff --git a/actionview/test/fixtures/test/render_file_inspect_local_assigns.erb b/actionview/test/fixtures/test/render_file_inspect_local_assigns.erb new file mode 100644 index 0000000000..aea5c351c5 --- /dev/null +++ b/actionview/test/fixtures/test/render_file_inspect_local_assigns.erb @@ -0,0 +1 @@ +<%= local_assigns.inspect.html_safe %>
\ No newline at end of file diff --git a/actionview/test/fixtures/test/render_file_instance_variable.erb b/actionview/test/fixtures/test/render_file_instance_variable.erb new file mode 100644 index 0000000000..5344ac8a66 --- /dev/null +++ b/actionview/test/fixtures/test/render_file_instance_variable.erb @@ -0,0 +1 @@ +<%= @foo %>
\ No newline at end of file diff --git a/actionview/test/fixtures/test/render_file_unicode_local.erb b/actionview/test/fixtures/test/render_file_unicode_local.erb new file mode 100644 index 0000000000..cbfd040a76 --- /dev/null +++ b/actionview/test/fixtures/test/render_file_unicode_local.erb @@ -0,0 +1 @@ +<%= 🎃 %>
\ No newline at end of file diff --git a/actionview/test/fixtures/test/render_file_with_ruby_keyword_locals.erb b/actionview/test/fixtures/test/render_file_with_ruby_keyword_locals.erb new file mode 100644 index 0000000000..7e3fe6c6d9 --- /dev/null +++ b/actionview/test/fixtures/test/render_file_with_ruby_keyword_locals.erb @@ -0,0 +1 @@ +The class is <%= local_assigns[:class] %>
\ No newline at end of file diff --git a/actionview/test/fixtures/test/streaming_with_locale.erb b/actionview/test/fixtures/test/streaming_with_locale.erb new file mode 100644 index 0000000000..b0f2b2f7e9 --- /dev/null +++ b/actionview/test/fixtures/test/streaming_with_locale.erb @@ -0,0 +1 @@ +view.locale: <%= I18n.locale %> diff --git a/actionview/test/fixtures/test/test_template_with_delegation_reserved_keywords.erb b/actionview/test/fixtures/test/test_template_with_delegation_reserved_keywords.erb new file mode 100644 index 0000000000..edfe52e422 --- /dev/null +++ b/actionview/test/fixtures/test/test_template_with_delegation_reserved_keywords.erb @@ -0,0 +1 @@ +<%= _ %> <%= arg %> <%= args %> <%= block %>
\ No newline at end of file diff --git a/actionview/test/fixtures/topic.rb b/actionview/test/fixtures/topic.rb index 9fa9746535..ff194ce567 100644 --- a/actionview/test/fixtures/topic.rb +++ b/actionview/test/fixtures/topic.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class Topic < ActiveRecord::Base - has_many :replies, :dependent => :destroy + has_many :replies, dependent: :destroy end diff --git a/actionview/test/lib/controller/fake_models.rb b/actionview/test/lib/controller/fake_models.rb index 65c68fc34a..f8b7ddaecc 100644 --- a/actionview/test/lib/controller/fake_models.rb +++ b/actionview/test/lib/controller/fake_models.rb @@ -1,12 +1,14 @@ +# frozen_string_literal: true + require "active_model" -class Customer < Struct.new(:name, :id) +Customer = Struct.new(:name, :id) do extend ActiveModel::Naming include ActiveModel::Conversion undef_method :to_json - def to_xml(options={}) + def to_xml(options = {}) if options[:builder] options[:builder].name name else @@ -14,7 +16,7 @@ class Customer < Struct.new(:name, :id) end end - def to_js(options={}) + def to_js(options = {}) "name: #{name.inspect}" end alias :to_text :to_js @@ -26,12 +28,16 @@ class Customer < Struct.new(:name, :id) def persisted? id.present? end -end -class GoodCustomer < Customer + def cache_key + name.to_s + end end -class Post < Struct.new(:title, :author_name, :body, :secret, :persisted, :written_on, :cost) +class BadCustomer < Customer; end +class GoodCustomer < Customer; end + +Post = Struct.new(:title, :author_name, :body, :secret, :persisted, :written_on, :cost) do extend ActiveModel::Naming include ActiveModel::Conversion extend ActiveModel::Translation @@ -80,7 +86,7 @@ class Comment def to_key; id ? [id] : nil end def save; @id = 1; @post_id = 1 end def persisted?; @id.present? end - def to_param; @id.to_s; end + def to_param; @id && @id.to_s; end def name @id.nil? ? "new #{self.class.name.downcase}" : "#{self.class.name.downcase} ##{@id}" end @@ -101,14 +107,13 @@ class Tag def to_key; id ? [id] : nil end def save; @id = 1; @post_id = 1 end def persisted?; @id.present? end - def to_param; @id; end + def to_param; @id && @id.to_s; end def value @id.nil? ? "new #{self.class.name.downcase}" : "#{self.class.name.downcase} ##{@id}" end attr_accessor :relevances def relevances_attributes=(attributes); end - end class CommentRelevance @@ -121,7 +126,7 @@ class CommentRelevance def to_key; id ? [id] : nil end def save; @id = 1; @comment_id = 1 end def persisted?; @id.present? end - def to_param; @id; end + def to_param; @id && @id.to_s; end def value @id.nil? ? "new #{self.class.name.downcase}" : "#{self.class.name.downcase} ##{@id}" end @@ -137,7 +142,7 @@ class TagRelevance def to_key; id ? [id] : nil end def save; @id = 1; @tag_id = 1 end def persisted?; @id.present? end - def to_param; @id; end + def to_param; @id && @id.to_s; end def value @id.nil? ? "new #{self.class.name.downcase}" : "#{self.class.name.downcase} ##{@id}" end @@ -164,7 +169,7 @@ module Blog true end - class Post < Struct.new(:title, :id) + Post = Struct.new(:title, :id) do extend ActiveModel::Naming include ActiveModel::Conversion @@ -184,14 +189,13 @@ class ArelLike end end -class Car < Struct.new(:color) -end +Car = Struct.new(:color) class Plane attr_reader :to_key def model_name - OpenStruct.new param_key: 'airplane' + OpenStruct.new param_key: "airplane" end def save diff --git a/actionview/test/template/active_model_helper_test.rb b/actionview/test/template/active_model_helper_test.rb index 55d62cf692..36afed6dd6 100644 --- a/actionview/test/template/active_model_helper_test.rb +++ b/actionview/test/template/active_model_helper_test.rb @@ -1,10 +1,12 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class ActiveModelHelperTest < ActionView::TestCase tests ActionView::Helpers::ActiveModelHelper silence_warnings do - class Post < Struct.new(:author_name, :body, :updated_at) + Post = Struct.new(:author_name, :body, :category, :published, :updated_at) do include ActiveModel::Conversion include ActiveModel::Validations @@ -20,10 +22,14 @@ class ActiveModelHelperTest < ActionView::TestCase @post = Post.new @post.errors[:author_name] << "can't be empty" @post.errors[:body] << "foo" + @post.errors[:category] << "must exist" + @post.errors[:published] << "must be accepted" @post.errors[:updated_at] << "bar" @post.author_name = "" @post.body = "Back to the hill and over it again!" + @post.category = "rails" + @post.published = false @post.updated_at = Date.new(2004, 6, 15) end @@ -50,28 +56,96 @@ class ActiveModelHelperTest < ActionView::TestCase def test_select_with_errors_and_blank_option expected_dom = %(<div class="field_with_errors"><select name="post[author_name]" id="post_author_name"><option value="">Choose one...</option>\n<option value="a">a</option>\n<option value="b">b</option></select></div>) - assert_dom_equal(expected_dom, select("post", "author_name", [:a, :b], :include_blank => 'Choose one...')) - assert_dom_equal(expected_dom, select("post", "author_name", [:a, :b], :prompt => 'Choose one...')) + assert_dom_equal(expected_dom, select("post", "author_name", [:a, :b], include_blank: "Choose one...")) + assert_dom_equal(expected_dom, select("post", "author_name", [:a, :b], prompt: "Choose one...")) + end + + def test_select_grouped_options_with_errors + grouped_options = [ + ["A", [["A1"], ["A2"]]], + ["B", [["B1"], ["B2"]]], + ] + + assert_dom_equal( + %(<div class="field_with_errors"><select name="post[category]" id="post_category"><optgroup label="A"><option value="A1">A1</option>\n<option value="A2">A2</option></optgroup><optgroup label="B"><option value="B1">B1</option>\n<option value="B2">B2</option></optgroup></select></div>), + select("post", "category", grouped_options) + ) + end + + def test_collection_select_with_errors + assert_dom_equal( + %(<div class="field_with_errors"><select name="post[author_name]" id="post_author_name"><option value="a">a</option>\n<option value="b">b</option></select></div>), + collection_select("post", "author_name", [:a, :b], :to_s, :to_s) + ) end def test_date_select_with_errors assert_dom_equal( %(<div class="field_with_errors"><select id="post_updated_at_1i" name="post[updated_at(1i)]">\n<option selected="selected" value="2004">2004</option>\n<option value="2005">2005</option>\n</select>\n<input id="post_updated_at_2i" name="post[updated_at(2i)]" type="hidden" value="6" />\n<input id="post_updated_at_3i" name="post[updated_at(3i)]" type="hidden" value="1" />\n</div>), - date_select("post", "updated_at", :discard_month => true, :discard_day => true, :start_year => 2004, :end_year => 2005) + date_select("post", "updated_at", discard_month: true, discard_day: true, start_year: 2004, end_year: 2005) ) end def test_datetime_select_with_errors assert_dom_equal( %(<div class="field_with_errors"><input id="post_updated_at_1i" name="post[updated_at(1i)]" type="hidden" value="2004" />\n<input id="post_updated_at_2i" name="post[updated_at(2i)]" type="hidden" value="6" />\n<input id="post_updated_at_3i" name="post[updated_at(3i)]" type="hidden" value="1" />\n<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n<option selected="selected" value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n</select>\n : <select id="post_updated_at_5i" name="post[updated_at(5i)]">\n<option selected="selected" value="00">00</option>\n</select>\n</div>), - datetime_select("post", "updated_at", :discard_year => true, :discard_month => true, :discard_day => true, :minute_step => 60) + datetime_select("post", "updated_at", discard_year: true, discard_month: true, discard_day: true, minute_step: 60) ) end def test_time_select_with_errors assert_dom_equal( %(<div class="field_with_errors"><input id="post_updated_at_1i" name="post[updated_at(1i)]" type="hidden" value="2004" />\n<input id="post_updated_at_2i" name="post[updated_at(2i)]" type="hidden" value="6" />\n<input id="post_updated_at_3i" name="post[updated_at(3i)]" type="hidden" value="15" />\n<select id="post_updated_at_4i" name="post[updated_at(4i)]">\n<option selected="selected" value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n</select>\n : <select id="post_updated_at_5i" name="post[updated_at(5i)]">\n<option selected="selected" value="00">00</option>\n</select>\n</div>), - time_select("post", "updated_at", :minute_step => 60) + time_select("post", "updated_at", minute_step: 60) + ) + end + + def test_label_with_errors + assert_dom_equal( + %(<div class="field_with_errors"><label for="post_body">Body</label></div>), + label("post", "body") + ) + end + + def test_check_box_with_errors + assert_dom_equal( + %(<input name="post[published]" type="hidden" value="0" /><div class="field_with_errors"><input type="checkbox" value="1" name="post[published]" id="post_published" /></div>), + check_box("post", "published") + ) + end + + def test_check_boxes_with_errors + assert_dom_equal( + %(<input name="post[published]" type="hidden" value="0" /><div class="field_with_errors"><input type="checkbox" value="1" name="post[published]" id="post_published" /></div><input name="post[published]" type="hidden" value="0" /><div class="field_with_errors"><input type="checkbox" value="1" name="post[published]" id="post_published" /></div>), + check_box("post", "published") + check_box("post", "published") + ) + end + + def test_radio_button_with_errors + assert_dom_equal( + %(<div class="field_with_errors"><input type="radio" value="rails" checked="checked" name="post[category]" id="post_category_rails" /></div>), + radio_button("post", "category", "rails") + ) + end + + def test_radio_buttons_with_errors + assert_dom_equal( + %(<div class="field_with_errors"><input type="radio" value="rails" checked="checked" name="post[category]" id="post_category_rails" /></div><div class="field_with_errors"><input type="radio" value="java" name="post[category]" id="post_category_java" /></div>), + radio_button("post", "category", "rails") + radio_button("post", "category", "java") + ) + end + + def test_collection_check_boxes_with_errors + assert_dom_equal( + %(<input type="hidden" name="post[category][]" value="" /><div class="field_with_errors"><input type="checkbox" value="ruby" name="post[category][]" id="post_category_ruby" /></div><label for="post_category_ruby">ruby</label><div class="field_with_errors"><input type="checkbox" value="java" name="post[category][]" id="post_category_java" /></div><label for="post_category_java">java</label>), + collection_check_boxes("post", "category", [:ruby, :java], :to_s, :to_s) + ) + end + + def test_collection_radio_buttons_with_errors + assert_dom_equal( + %(<input type="hidden" name="post[category]" value="" /><div class="field_with_errors"><input type="radio" value="ruby" name="post[category]" id="post_category_ruby" /></div><label for="post_category_ruby">ruby</label><div class="field_with_errors"><input type="radio" value="java" name="post[category]" id="post_category_java" /></div><label for="post_category_java">java</label>), + collection_radio_buttons("post", "category", [:ruby, :java], :to_s, :to_s) ) end @@ -95,5 +169,4 @@ class ActiveModelHelperTest < ActionView::TestCase ensure ActionView::Base.field_error_proc = old_proc if old_proc end - end diff --git a/actionview/test/template/asset_tag_helper_test.rb b/actionview/test/template/asset_tag_helper_test.rb index 8bfd19eb26..284dacf2d4 100644 --- a/actionview/test/template/asset_tag_helper_test.rb +++ b/actionview/test/template/asset_tag_helper_test.rb @@ -1,5 +1,7 @@ -require 'abstract_unit' -require 'active_support/ordered_options' +# frozen_string_literal: true + +require "abstract_unit" +require "active_support/ordered_options" class AssetTagHelperTest < ActionView::TestCase tests ActionView::Helpers::AssetTagHelper @@ -13,10 +15,11 @@ class AssetTagHelperTest < ActionView::TestCase @request = Class.new do attr_accessor :script_name - def protocol() 'http://' end + def protocol() "http://" end def ssl?() false end - def host_with_port() 'localhost' end - def base_url() 'http://www.example.com' end + def host_with_port() "localhost" end + def base_url() "http://www.example.com" end + def send_early_hints(links) end end.new @controller.request = @request @@ -53,6 +56,7 @@ class AssetTagHelperTest < ActionView::TestCase %(auto_discovery_link_tag) => %(<link href="http://www.example.com" rel="alternate" title="RSS" type="application/rss+xml" />), %(auto_discovery_link_tag(:rss)) => %(<link href="http://www.example.com" rel="alternate" title="RSS" type="application/rss+xml" />), %(auto_discovery_link_tag(:atom)) => %(<link href="http://www.example.com" rel="alternate" title="ATOM" type="application/atom+xml" />), + %(auto_discovery_link_tag(:json)) => %(<link href="http://www.example.com" rel="alternate" title="JSON" type="application/json" />), %(auto_discovery_link_tag(:rss, :action => "feed")) => %(<link href="http://www.example.com" rel="alternate" title="RSS" type="application/rss+xml" />), %(auto_discovery_link_tag(:rss, "http://localhost/feed")) => %(<link href="http://localhost/feed" rel="alternate" title="RSS" type="application/rss+xml" />), %(auto_discovery_link_tag(:rss, "//localhost/feed")) => %(<link href="//localhost/feed" rel="alternate" title="RSS" type="application/rss+xml" />), @@ -180,23 +184,26 @@ class AssetTagHelperTest < ActionView::TestCase } ImageLinkToTag = { - %(image_tag("xml.png")) => %(<img alt="Xml" src="/images/xml.png" />), + %(image_tag("xml.png")) => %(<img 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" />), - %(image_tag("error.png", "size" => "x")) => %(<img alt="Error" src="/images/error.png" />), - %(image_tag("google.com.png")) => %(<img alt="Google.com" src="/images/google.com.png" />), - %(image_tag("slash..png")) => %(<img alt="Slash." src="/images/slash..png" />), - %(image_tag(".pdf.png")) => %(<img alt=".pdf" src="/images/.pdf.png" />), - %(image_tag("http://www.rubyonrails.com/images/rails.png")) => %(<img alt="Rails" src="http://www.rubyonrails.com/images/rails.png" />), - %(image_tag("//www.rubyonrails.com/images/rails.png")) => %(<img alt="Rails" src="//www.rubyonrails.com/images/rails.png" />), + %(image_tag("gold.png", :size => "20")) => %(<img height="20" src="/images/gold.png" width="20" />), + %(image_tag("gold.png", :size => 20)) => %(<img height="20" src="/images/gold.png" width="20" />), + %(image_tag("gold.png", :size => "45x70")) => %(<img height="70" src="/images/gold.png" width="45" />), + %(image_tag("gold.png", "size" => "45x70")) => %(<img height="70" src="/images/gold.png" width="45" />), + %(image_tag("error.png", "size" => "45 x 70")) => %(<img src="/images/error.png" />), + %(image_tag("error.png", "size" => "x")) => %(<img src="/images/error.png" />), + %(image_tag("google.com.png")) => %(<img src="/images/google.com.png" />), + %(image_tag("slash..png")) => %(<img src="/images/slash..png" />), + %(image_tag(".pdf.png")) => %(<img src="/images/.pdf.png" />), + %(image_tag("http://www.rubyonrails.com/images/rails.png")) => %(<img src="http://www.rubyonrails.com/images/rails.png" />), + %(image_tag("//www.rubyonrails.com/images/rails.png")) => %(<img src="//www.rubyonrails.com/images/rails.png" />), %(image_tag("mouse.png", :alt => nil)) => %(<img src="/images/mouse.png" />), %(image_tag("data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==", :alt => nil)) => %(<img src="data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" />), %(image_tag("")) => %(<img src="" />), - %(image_tag("gold.png", data: { title: 'Rails Application' })) => %(<img data-title="Rails Application" src="/images/gold.png" alt="Gold" />) + %(image_tag("gold.png", data: { title: 'Rails Application' })) => %(<img data-title="Rails Application" src="/images/gold.png" />), + %(image_tag("rss.gif", srcset: "/assets/pic_640.jpg 640w, /assets/pic_1024.jpg 1024w")) => %(<img srcset="/assets/pic_640.jpg 640w, /assets/pic_1024.jpg 1024w" src="/images/rss.gif" />), + %(image_tag("rss.gif", srcset: { "pic_640.jpg" => "640w", "pic_1024.jpg" => "1024w" })) => %(<img srcset="/images/pic_640.jpg 640w, /images/pic_1024.jpg 1024w" src="/images/rss.gif" />), + %(image_tag("rss.gif", srcset: [["pic_640.jpg", "640w"], ["pic_1024.jpg", "1024w"]])) => %(<img srcset="/images/pic_640.jpg 640w, /images/pic_1024.jpg 1024w" src="/images/rss.gif" />) } FaviconLinkToTag = { @@ -207,6 +214,17 @@ class AssetTagHelperTest < ActionView::TestCase %(favicon_link_tag 'mb-icon.png', :rel => 'apple-touch-icon', :type => 'image/png') => %(<link href="/images/mb-icon.png" rel="apple-touch-icon" type="image/png" />) } + PreloadLinkToTag = { + %(preload_link_tag '/styles/custom_theme.css') => %(<link rel="preload" href="/styles/custom_theme.css" as="style" type="text/css" />), + %(preload_link_tag '/videos/video.webm') => %(<link rel="preload" href="/videos/video.webm" as="video" type="video/webm" />), + %(preload_link_tag '/posts.json', as: 'fetch') => %(<link rel="preload" href="/posts.json" as="fetch" type="application/json" />), + %(preload_link_tag '/users', as: 'fetch', type: 'application/json') => %(<link rel="preload" href="/users" as="fetch" type="application/json" />), + %(preload_link_tag '//example.com/map?callback=initMap', as: 'fetch', type: 'application/javascript') => %(<link rel="preload" href="//example.com/map?callback=initMap" as="fetch" type="application/javascript" />), + %(preload_link_tag '//example.com/font.woff2') => %(<link rel="preload" href="//example.com/font.woff2" as="font" type="font/woff2" crossorigin="anonymous"/>), + %(preload_link_tag '//example.com/font.woff2', crossorigin: 'use-credentials') => %(<link rel="preload" href="//example.com/font.woff2" as="font" type="font/woff2" crossorigin="use-credentials" />), + %(preload_link_tag '/media/audio.ogg', nopush: true) => %(<link rel="preload" href="/media/audio.ogg" as="audio" type="audio/ogg" />) + } + VideoPathToTag = { %(video_path("xml")) => %(/videos/xml), %(video_path("xml.ogg")) => %(/videos/xml.ogg), @@ -238,7 +256,7 @@ class AssetTagHelperTest < ActionView::TestCase VideoLinkToTag = { %(video_tag("xml.ogg")) => %(<video src="/videos/xml.ogg"></video>), %(video_tag("rss.m4v", :autoplay => true, :controls => true)) => %(<video autoplay="autoplay" controls="controls" src="/videos/rss.m4v"></video>), - %(video_tag("rss.m4v", :autobuffer => true)) => %(<video autobuffer="autobuffer" src="/videos/rss.m4v"></video>), + %(video_tag("rss.m4v", :preload => 'none')) => %(<video preload="none" src="/videos/rss.m4v"></video>), %(video_tag("gold.m4v", :size => "160x120")) => %(<video height="120" src="/videos/gold.m4v" width="160"></video>), %(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>), @@ -288,7 +306,7 @@ class AssetTagHelperTest < ActionView::TestCase %(audio_tag("//media.rubyonrails.org/audio/rails_blog_2.mov")) => %(<audio src="//media.rubyonrails.org/audio/rails_blog_2.mov"></audio>), %(audio_tag("audio.mp3", "audio.ogg")) => %(<audio><source src="/audios/audio.mp3" /><source src="/audios/audio.ogg" /></audio>), %(audio_tag(["audio.mp3", "audio.ogg"])) => %(<audio><source src="/audios/audio.mp3" /><source src="/audios/audio.ogg" /></audio>), - %(audio_tag(["audio.mp3", "audio.ogg"], :autobuffer => true, :controls => true)) => %(<audio autobuffer="autobuffer" controls="controls"><source src="/audios/audio.mp3" /><source src="/audios/audio.ogg" /></audio>) + %(audio_tag(["audio.mp3", "audio.ogg"], :preload => 'none', :controls => true)) => %(<audio preload="none" controls="controls"><source src="/audios/audio.mp3" /><source src="/audios/audio.ogg" /></audio>) } FontPathToTag = { @@ -299,6 +317,24 @@ class AssetTagHelperTest < ActionView::TestCase %(font_path("font.ttf?123")) => %(/fonts/font.ttf?123) } + FontUrlToTag = { + %(font_url("font.eot")) => %(http://www.example.com/fonts/font.eot), + %(font_url("font.eot#iefix")) => %(http://www.example.com/fonts/font.eot#iefix), + %(font_url("font.woff")) => %(http://www.example.com/fonts/font.woff), + %(font_url("font.ttf")) => %(http://www.example.com/fonts/font.ttf), + %(font_url("font.ttf?123")) => %(http://www.example.com/fonts/font.ttf?123), + %(font_url("font.ttf", host: "http://assets.example.com")) => %(http://assets.example.com/fonts/font.ttf) + } + + UrlToFontToTag = { + %(url_to_font("font.eot")) => %(http://www.example.com/fonts/font.eot), + %(url_to_font("font.eot#iefix")) => %(http://www.example.com/fonts/font.eot#iefix), + %(url_to_font("font.woff")) => %(http://www.example.com/fonts/font.woff), + %(url_to_font("font.ttf")) => %(http://www.example.com/fonts/font.ttf), + %(url_to_font("font.ttf?123")) => %(http://www.example.com/fonts/font.ttf?123), + %(url_to_font("font.ttf", host: "http://assets.example.com")) => %(http://assets.example.com/fonts/font.ttf) + } + def test_autodiscovery_link_tag_with_unknown_type_but_not_pass_type_option_key assert_raise(ArgumentError) do auto_discovery_link_tag(:xml) @@ -306,7 +342,7 @@ class AssetTagHelperTest < ActionView::TestCase end def test_autodiscovery_link_tag_with_unknown_type - result = auto_discovery_link_tag(:xml, '/feed.xml', :type => 'application/xml') + result = auto_discovery_link_tag(:xml, "/feed.xml", type: "application/xml") expected = %(<link href="/feed.xml" rel="alternate" title="XML" type="application/xml" />) assert_dom_equal expected, result end @@ -322,18 +358,18 @@ class AssetTagHelperTest < ActionView::TestCase def test_asset_path_tag_to_not_create_duplicate_slashes @controller.config.asset_host = "host/" - assert_dom_equal('http://host/foo', asset_path("foo")) + assert_dom_equal("http://host/foo", asset_path("foo")) - @controller.config.relative_url_root = '/some/root/' - assert_dom_equal('http://host/some/root/foo', asset_path("foo")) + @controller.config.relative_url_root = "/some/root/" + assert_dom_equal("http://host/some/root/foo", asset_path("foo")) end def test_compute_asset_public_path assert_equal "/robots.txt", compute_asset_path("robots.txt") assert_equal "/robots.txt", compute_asset_path("/robots.txt") - assert_equal "/javascripts/foo.js", compute_asset_path("foo.js", :type => :javascript) - assert_equal "/javascripts/foo.js", compute_asset_path("/foo.js", :type => :javascript) - assert_equal "/stylesheets/foo.css", compute_asset_path("foo.css", :type => :stylesheet) + assert_equal "/javascripts/foo.js", compute_asset_path("foo.js", type: :javascript) + assert_equal "/javascripts/foo.js", compute_asset_path("/foo.js", type: :javascript) + assert_equal "/stylesheets/foo.css", compute_asset_path("foo.css", type: :stylesheet) end def test_auto_discovery_link_tag @@ -362,11 +398,11 @@ class AssetTagHelperTest < ActionView::TestCase def test_javascript_include_tag_with_missing_source assert_nothing_raised { - javascript_include_tag('missing_security_guard') + javascript_include_tag("missing_security_guard") } assert_nothing_raised { - javascript_include_tag('http://example.com/css/missing_security_guard') + javascript_include_tag("http://example.com/css/missing_security_guard") } end @@ -376,13 +412,13 @@ class AssetTagHelperTest < ActionView::TestCase def test_javascript_include_tag_relative_protocol @controller.config.asset_host = "assets.example.com" - assert_dom_equal %(<script src="//assets.example.com/javascripts/prototype.js"></script>), javascript_include_tag('prototype', protocol: :relative) + assert_dom_equal %(<script src="//assets.example.com/javascripts/prototype.js"></script>), javascript_include_tag("prototype", protocol: :relative) end def test_javascript_include_tag_default_protocol @controller.config.asset_host = "assets.example.com" @controller.config.default_asset_host_protocol = :relative - assert_dom_equal %(<script src="//assets.example.com/javascripts/prototype.js"></script>), javascript_include_tag('prototype') + assert_dom_equal %(<script src="//assets.example.com/javascripts/prototype.js"></script>), javascript_include_tag("prototype") end def test_stylesheet_path @@ -407,36 +443,49 @@ class AssetTagHelperTest < ActionView::TestCase def test_stylesheet_link_tag_with_missing_source assert_nothing_raised { - stylesheet_link_tag('missing_security_guard') + stylesheet_link_tag("missing_security_guard") } assert_nothing_raised { - stylesheet_link_tag('http://example.com/css/missing_security_guard') + stylesheet_link_tag("http://example.com/css/missing_security_guard") } end + def test_stylesheet_link_tag_without_request + @request = nil + assert_dom_equal( + %(<link rel="stylesheet" media="screen" href="/stylesheets/foo.css" />), + stylesheet_link_tag("foo.css") + ) + end + def test_stylesheet_link_tag_is_html_safe - assert stylesheet_link_tag('dir/file').html_safe? - assert stylesheet_link_tag('dir/other/file', 'dir/file2').html_safe? + assert stylesheet_link_tag("dir/file").html_safe? + assert stylesheet_link_tag("dir/other/file", "dir/file2").html_safe? end def test_stylesheet_link_tag_escapes_options - assert_dom_equal %(<link href="/file.css" media="<script>" rel="stylesheet" />), stylesheet_link_tag('/file', :media => '<script>') + assert_dom_equal %(<link href="/file.css" media="<script>" rel="stylesheet" />), stylesheet_link_tag("/file", media: "<script>") end def test_stylesheet_link_tag_should_not_output_the_same_asset_twice - assert_dom_equal %(<link href="/stylesheets/wellington.css" media="screen" rel="stylesheet" />\n<link href="/stylesheets/amsterdam.css" media="screen" rel="stylesheet" />), stylesheet_link_tag('wellington', 'wellington', 'amsterdam') + assert_dom_equal %(<link href="/stylesheets/wellington.css" media="screen" rel="stylesheet" />\n<link href="/stylesheets/amsterdam.css" media="screen" rel="stylesheet" />), stylesheet_link_tag("wellington", "wellington", "amsterdam") end def test_stylesheet_link_tag_with_relative_protocol @controller.config.asset_host = "assets.example.com" - assert_dom_equal %(<link href="//assets.example.com/stylesheets/wellington.css" media="screen" rel="stylesheet" />), stylesheet_link_tag('wellington', protocol: :relative) + assert_dom_equal %(<link href="//assets.example.com/stylesheets/wellington.css" media="screen" rel="stylesheet" />), stylesheet_link_tag("wellington", protocol: :relative) end def test_stylesheet_link_tag_with_default_protocol @controller.config.asset_host = "assets.example.com" @controller.config.default_asset_host_protocol = :relative - assert_dom_equal %(<link href="//assets.example.com/stylesheets/wellington.css" media="screen" rel="stylesheet" />), stylesheet_link_tag('wellington') + assert_dom_equal %(<link href="//assets.example.com/stylesheets/wellington.css" media="screen" rel="stylesheet" />), stylesheet_link_tag("wellington") + end + + def test_javascript_include_tag_without_request + @request = nil + assert_dom_equal %(<script src="/javascripts/foo.js"></script>), javascript_include_tag("foo.js") end def test_image_path @@ -456,12 +505,22 @@ class AssetTagHelperTest < ActionView::TestCase end def test_image_alt - [nil, '/', '/foo/bar/', 'foo/bar/'].each do |prefix| - assert_equal 'Rails', image_alt("#{prefix}rails.png") - assert_equal 'Rails', image_alt("#{prefix}rails-9c0a079bdd7701d7e729bd956823d153.png") - assert_equal 'Rails', image_alt("#{prefix}rails-f56ef62bc41b040664e801a38f068082a75d506d9048307e8096737463503d0b.png") - assert_equal 'Long file name with hyphens', image_alt("#{prefix}long-file-name-with-hyphens.png") - assert_equal 'Long file name with underscores', image_alt("#{prefix}long_file_name_with_underscores.png") + [nil, "/", "/foo/bar/", "foo/bar/"].each do |prefix| + assert_deprecated do + assert_equal "Rails", image_alt("#{prefix}rails.png") + end + assert_deprecated do + assert_equal "Rails", image_alt("#{prefix}rails-9c0a079bdd7701d7e729bd956823d153.png") + end + assert_deprecated do + assert_equal "Rails", image_alt("#{prefix}rails-f56ef62bc41b040664e801a38f068082a75d506d9048307e8096737463503d0b.png") + end + assert_deprecated do + assert_equal "Long file name with hyphens", image_alt("#{prefix}long-file-name-with-hyphens.png") + end + assert_deprecated do + assert_equal "Long file name with underscores", image_alt("#{prefix}long_file_name_with_underscores.png") + end end end @@ -470,14 +529,14 @@ class AssetTagHelperTest < ActionView::TestCase end def test_image_tag_does_not_modify_options - options = {:size => '16x10'} - image_tag('icon', options) - assert_equal({:size => '16x10'}, options) + options = { size: "16x10" } + image_tag("icon", options) + 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") + 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) @@ -487,6 +546,10 @@ class AssetTagHelperTest < ActionView::TestCase FaviconLinkToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) } end + def test_preload_link_tag + PreloadLinkToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) } + end + def test_video_path VideoPathToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) } end @@ -531,12 +594,20 @@ class AssetTagHelperTest < ActionView::TestCase FontPathToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) } end + def test_font_url + FontUrlToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) } + end + + def test_url_to_font_alias_for_font_url + UrlToFontToTag.each { |method, tag| assert_dom_equal(tag, eval(method)) } + end + def test_video_audio_tag_does_not_modify_options - options = {:autoplay => true} - video_tag('video', options) - assert_equal({:autoplay => true}, options) - audio_tag('audio', options) - assert_equal({:autoplay => true}, options) + options = { autoplay: true } + video_tag("video", options) + assert_equal({ autoplay: true }, options) + audio_tag("audio", options) + assert_equal({ autoplay: true }, options) end def test_image_tag_interpreting_email_cid_correctly @@ -545,11 +616,11 @@ class AssetTagHelperTest < ActionView::TestCase end def test_image_tag_interpreting_email_adding_optional_alt_tag - assert_equal '<img alt="Image" src="cid:thi%25%25sis@acontentid" />', image_tag("cid:thi%25%25sis@acontentid", :alt => "Image") + assert_equal '<img alt="Image" src="cid:thi%25%25sis@acontentid" />', image_tag("cid:thi%25%25sis@acontentid", alt: "Image") end def test_should_not_modify_source_string - source = '/images/rails.png' + source = "/images/rails.png" copy = source.dup image_tag(source) assert_equal copy, source @@ -557,13 +628,10 @@ class AssetTagHelperTest < ActionView::TestCase class PlaceholderImage def blank?; true; end - def to_s; 'no-image-yet.png'; end - end - def test_image_tag_with_blank_placeholder - assert_equal '<img alt="" src="/images/no-image-yet.png" />', image_tag(PlaceholderImage.new, alt: "") + def to_s; "no-image-yet.png"; end end def test_image_path_with_blank_placeholder - assert_equal '/images/no-image-yet.png', image_path(PlaceholderImage.new) + assert_equal "/images/no-image-yet.png", image_path(PlaceholderImage.new) end def test_image_path_with_asset_host_proc_returning_nil @@ -614,7 +682,9 @@ class AssetTagHelperNonVhostTest < ActionView::TestCase @controller = BasicController.new @controller.config.relative_url_root = "/collaboration/hieraki" - @request = Struct.new(:protocol, :base_url).new("gopher://", "gopher://www.example.com") + @request = Struct.new(:protocol, :base_url) do + def send_early_hints(links); end + end.new("gopher://", "gopher://www.example.com") @controller.request = @request end @@ -630,15 +700,15 @@ class AssetTagHelperNonVhostTest < ActionView::TestCase end def test_should_return_nothing_if_asset_host_isnt_configured - assert_equal nil, compute_asset_host("foo") + assert_nil compute_asset_host("foo") end def test_should_current_request_host_is_always_returned_for_request - assert_equal "gopher://www.example.com", compute_asset_host("foo", :protocol => :request) + assert_equal "gopher://www.example.com", compute_asset_host("foo", protocol: :request) end def test_should_return_custom_host_if_passed_in_options - assert_equal "http://custom.example.com", compute_asset_host("foo", :host => "http://custom.example.com") + assert_equal "http://custom.example.com", compute_asset_host("foo", host: "http://custom.example.com") end def test_should_ignore_relative_root_path_on_complete_url @@ -652,12 +722,12 @@ class AssetTagHelperNonVhostTest < ActionView::TestCase def test_should_return_relative_asset_host @controller.config.asset_host = "assets.example.com" - assert_equal "//assets.example.com", compute_asset_host("foo", :protocol => :relative) + assert_equal "//assets.example.com", compute_asset_host("foo", protocol: :relative) end def test_should_return_custom_protocol_asset_host @controller.config.asset_host = "assets.example.com" - assert_equal "ftp://assets.example.com", compute_asset_host("foo", :protocol => "ftp") + assert_equal "ftp://assets.example.com", compute_asset_host("foo", protocol: "ftp") end def test_should_compute_proper_path_with_asset_host @@ -708,26 +778,26 @@ class AssetTagHelperNonVhostTest < ActionView::TestCase end def test_should_wildcard_asset_host - @controller.config.asset_host = 'http://a%d.example.com' - assert_match(%r(http://a[0123].example.com), compute_asset_host("foo")) + @controller.config.asset_host = "http://a%d.example.com" + assert_match(%r(http://a[0123]\.example\.com), compute_asset_host("foo")) end def test_should_wildcard_asset_host_between_zero_and_four - @controller.config.asset_host = 'http://a%d.example.com' - assert_match(%r(http://a[0123].example.com/collaboration/hieraki/images/xml.png), image_path('xml.png')) - assert_match(%r(http://a[0123].example.com/collaboration/hieraki/images/xml.png), image_url('xml.png')) + @controller.config.asset_host = "http://a%d.example.com" + assert_match(%r(http://a[0123]\.example\.com/collaboration/hieraki/images/xml\.png), image_path("xml.png")) + assert_match(%r(http://a[0123]\.example\.com/collaboration/hieraki/images/xml\.png), image_url("xml.png")) end def test_asset_host_without_protocol_should_be_protocol_relative - @controller.config.asset_host = 'a.example.com' - assert_equal 'gopher://a.example.com/collaboration/hieraki/images/xml.png', image_path('xml.png') - assert_equal 'gopher://a.example.com/collaboration/hieraki/images/xml.png', image_url('xml.png') + @controller.config.asset_host = "a.example.com" + assert_equal "gopher://a.example.com/collaboration/hieraki/images/xml.png", image_path("xml.png") + assert_equal "gopher://a.example.com/collaboration/hieraki/images/xml.png", image_url("xml.png") end def test_asset_host_without_protocol_should_be_protocol_relative_even_if_path_present - @controller.config.asset_host = 'a.example.com/files/go/here' - assert_equal 'gopher://a.example.com/files/go/here/collaboration/hieraki/images/xml.png', image_path('xml.png') - assert_equal 'gopher://a.example.com/files/go/here/collaboration/hieraki/images/xml.png', image_url('xml.png') + @controller.config.asset_host = "a.example.com/files/go/here" + assert_equal "gopher://a.example.com/files/go/here/collaboration/hieraki/images/xml.png", image_path("xml.png") + assert_equal "gopher://a.example.com/files/go/here/collaboration/hieraki/images/xml.png", image_url("xml.png") end def test_assert_css_and_js_of_the_same_name_return_correct_extension @@ -736,6 +806,23 @@ class AssetTagHelperNonVhostTest < ActionView::TestCase end end +class AssetTagHelperWithoutRequestTest < ActionView::TestCase + tests ActionView::Helpers::AssetTagHelper + + undef :request + + def test_stylesheet_link_tag_without_request + assert_dom_equal( + %(<link rel="stylesheet" media="screen" href="/stylesheets/foo.css" />), + stylesheet_link_tag("foo.css") + ) + end + + def test_javascript_include_tag_without_request + assert_dom_equal %(<script src="/javascripts/foo.js"></script>), javascript_include_tag("foo.js") + end +end + class AssetUrlHelperControllerTest < ActionView::TestCase tests ActionView::Helpers::AssetUrlHelper @@ -747,10 +834,10 @@ class AssetUrlHelperControllerTest < ActionView::TestCase @request = Class.new do attr_accessor :script_name - def protocol() 'http://' end + def protocol() "http://" end def ssl?() false end - def host_with_port() 'www.example.com' end - def base_url() 'http://www.example.com' end + def host_with_port() "www.example.com" end + def base_url() "http://www.example.com" end end.new @controller.request = @request @@ -813,6 +900,6 @@ class AssetUrlHelperEmptyModuleTest < ActionView::TestCase end assert @module.config.asset_host - assert_equal "http://custom.example.com/foo", @module.asset_url("foo", :host => "http://custom.example.com") + assert_equal "http://custom.example.com/foo", @module.asset_url("foo", host: "http://custom.example.com") end end diff --git a/actionview/test/template/atom_feed_helper_test.rb b/actionview/test/template/atom_feed_helper_test.rb index 591cd71404..1be20dcaae 100644 --- a/actionview/test/template/atom_feed_helper_test.rb +++ b/actionview/test/template/atom_feed_helper_test.rb @@ -1,6 +1,8 @@ -require 'abstract_unit' +# frozen_string_literal: true -class Scroll < Struct.new(:id, :to_param, :title, :body, :updated_at, :created_at) +require "abstract_unit" + +Scroll = Struct.new(:id, :to_param, :title, :body, :updated_at, :created_at) do extend ActiveModel::Naming include ActiveModel::Conversion @@ -28,7 +30,7 @@ class ScrollsController < ActionController::Base end end EOT - FEEDS["entry_options"] = <<-EOT + FEEDS["entry_options"] = <<-EOT atom_feed do |feed| feed.title("My great blog!") feed.updated(@scrolls.first.created_at) @@ -45,7 +47,7 @@ class ScrollsController < ActionController::Base end end EOT - FEEDS["entry_type_options"] = <<-EOT + FEEDS["entry_type_options"] = <<-EOT atom_feed(:schema_date => '2008') do |feed| feed.title("My great blog!") feed.updated(@scrolls.first.created_at) @@ -62,7 +64,7 @@ class ScrollsController < ActionController::Base end end EOT - FEEDS["entry_url_false_option"] = <<-EOT + FEEDS["entry_url_false_option"] = <<-EOT atom_feed do |feed| feed.title("My great blog!") feed.updated(@scrolls.first.created_at) @@ -79,7 +81,7 @@ class ScrollsController < ActionController::Base end end EOT - FEEDS["xml_block"] = <<-EOT + FEEDS["xml_block"] = <<-EOT atom_feed do |feed| feed.title("My great blog!") feed.updated(@scrolls.first.created_at) @@ -96,7 +98,7 @@ class ScrollsController < ActionController::Base end end EOT - FEEDS["feed_with_atomPub_namespace"] = <<-EOT + FEEDS["feed_with_atomPub_namespace"] = <<-EOT 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!") @@ -115,7 +117,7 @@ class ScrollsController < ActionController::Base end end EOT - FEEDS["feed_with_overridden_ids"] = <<-EOT + 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) @@ -169,7 +171,7 @@ class ScrollsController < ActionController::Base end end EOT - FEEDS["feed_with_xhtml_content"] = <<-'EOT' + FEEDS["feed_with_xhtml_content"] = <<-'EOT' atom_feed do |feed| feed.title("My great blog!") feed.updated(@scrolls.first.created_at) @@ -191,10 +193,10 @@ class ScrollsController < ActionController::Base end end EOT - FEEDS["provide_builder"] = <<-'EOT' + FEEDS["provide_builder"] = <<-'EOT' # we pass in the new_xml to the helper so it doesn't # call anything on the original builder - new_xml = Builder::XmlMarkup.new(:target=>'') + new_xml = Builder::XmlMarkup.new(:target=>''.dup) atom_feed(:xml => new_xml) do |feed| feed.title("My great blog!") feed.updated(@scrolls.first.created_at) @@ -217,7 +219,7 @@ class ScrollsController < ActionController::Base Scroll.new(2, "2", "Hello Two", "Something Boring", Time.utc(2007, 12, 12, 15)), ] - render :inline => FEEDS[params[:id]], :type => :builder + render inline: FEEDS[params[:id]], type: :builder end end @@ -278,22 +280,22 @@ class AtomFeedTest < ActionController::TestCase def test_feed_id_should_be_a_valid_tag with_restful_routing(:scrolls) do get :index, params: { id: "defaults" } - assert_select "id", :text => "tag:www.nextangle.com,2008:/scrolls?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, 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" + 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 end def test_feed_should_allow_nested_xml_blocks with_restful_routing(:scrolls) do get :index, params: { id: "xml_block" } - assert_select "author name", :text => "DHH" + assert_select "author name", text: "DHH" end end @@ -301,31 +303,31 @@ class AtomFeedTest < ActionController::TestCase with_restful_routing(:scrolls) do 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 + 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 end end def test_feed_should_allow_overriding_ids with_restful_routing(:scrolls) do 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" + 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" end end def test_feed_xml_processing_instructions with_restful_routing(:scrolls) do - get :index, params: { 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 + assert_match %r{<\?xml-stylesheet [^\?]*href="t\.css"}, @response.body end end def test_feed_xml_processing_instructions_duplicate_targets with_restful_routing(:scrolls) do - get :index, params: { 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 @@ -334,29 +336,29 @@ class AtomFeedTest < ActionController::TestCase def test_feed_xhtml with_restful_routing(:scrolls) do 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/ + assert_match %r{xmlns="http://www\.w3\.org/1999/xhtml"}, @response.body + assert_select "summary", text: /Something Boring/ + assert_select "summary", text: /after 2/ end end def test_feed_entry_type_option_default_to_text_html with_restful_routing(:scrolls) do - get :index, params: { 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, params: { 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' } + get :index, params: { id: "entry_url_false_option" } assert_select "entry link", false end end diff --git a/actionview/test/template/capture_helper_test.rb b/actionview/test/template/capture_helper_test.rb index ffaf773c53..8a1c00fd00 100644 --- a/actionview/test/template/capture_helper_test.rb +++ b/actionview/test/template/capture_helper_test.rb @@ -1,4 +1,6 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class CaptureHelperTest < ActionView::TestCase def setup @@ -10,18 +12,18 @@ class CaptureHelperTest < ActionView::TestCase def test_capture_captures_the_temporary_output_buffer_in_its_block assert_nil @av.output_buffer string = @av.capture do - @av.output_buffer << 'foo' - @av.output_buffer << 'bar' + @av.output_buffer << "foo" + @av.output_buffer << "bar" end assert_nil @av.output_buffer - assert_equal 'foobar', string + assert_equal "foobar", string end def test_capture_captures_the_value_returned_by_the_block_if_the_temporary_buffer_is_blank - string = @av.capture('foo', 'bar') do |a, b| + string = @av.capture("foo", "bar") do |a, b| a + b end - assert_equal 'foobar', string + assert_equal "foobar", string end def test_capture_returns_nil_if_the_returned_value_is_not_a_string @@ -29,121 +31,121 @@ class CaptureHelperTest < ActionView::TestCase end def test_capture_escapes_html - string = @av.capture { '<em>bar</em>' } - assert_equal '<em>bar</em>', string + string = @av.capture { "<em>bar</em>" } + assert_equal "<em>bar</em>", string end def test_capture_doesnt_escape_twice - string = @av.capture { raw('<em>bar</em>') } - assert_equal '<em>bar</em>', string + string = @av.capture { raw("<em>bar</em>") } + assert_equal "<em>bar</em>", string end def test_capture_used_for_read content_for :foo, "foo" assert_equal "foo", content_for(:foo) - content_for(:bar){ "bar" } + content_for(:bar) { "bar" } assert_equal "bar", content_for(:bar) end def test_content_for_with_multiple_calls assert ! content_for?(:title) - content_for :title, 'foo' - content_for :title, 'bar' - assert_equal 'foobar', content_for(:title) + content_for :title, "foo" + content_for :title, "bar" + assert_equal "foobar", content_for(:title) end def test_content_for_with_multiple_calls_and_flush assert ! content_for?(:title) - content_for :title, 'foo' - content_for :title, 'bar', flush: true - assert_equal 'bar', content_for(:title) + content_for :title, "foo" + content_for :title, "bar", flush: true + assert_equal "bar", content_for(:title) end def test_content_for_with_block assert ! content_for?(:title) content_for :title do - output_buffer << 'foo' - output_buffer << 'bar' + output_buffer << "foo" + output_buffer << "bar" nil end - assert_equal 'foobar', content_for(:title) + assert_equal "foobar", content_for(:title) end def test_content_for_with_block_and_multiple_calls_with_flush assert ! content_for?(:title) content_for :title do - 'foo' + "foo" end content_for :title, flush: true do - 'bar' + "bar" end - assert_equal 'bar', content_for(:title) + assert_equal "bar", content_for(:title) end def test_content_for_with_block_and_multiple_calls_with_flush_nil_content assert ! content_for?(:title) content_for :title do - 'foo' + "foo" end content_for :title, nil, flush: true do - 'bar' + "bar" end - assert_equal 'bar', content_for(:title) + assert_equal "bar", content_for(:title) end def test_content_for_with_block_and_multiple_calls_without_flush assert ! content_for?(:title) content_for :title do - 'foo' + "foo" end content_for :title, flush: false do - 'bar' + "bar" end - assert_equal 'foobar', content_for(:title) + assert_equal "foobar", content_for(:title) end def test_content_for_with_whitespace_block assert ! content_for?(:title) - content_for :title, 'foo' + content_for :title, "foo" content_for :title do output_buffer << " \n " nil end - content_for :title, 'bar' - assert_equal 'foobar', content_for(:title) + content_for :title, "bar" + assert_equal "foobar", content_for(:title) end def test_content_for_with_whitespace_block_and_flush assert ! content_for?(:title) - content_for :title, 'foo' + content_for :title, "foo" content_for :title, flush: true do output_buffer << " \n " nil end - content_for :title, 'bar', flush: true - assert_equal 'bar', content_for(:title) + content_for :title, "bar", flush: true + assert_equal "bar", content_for(:title) end def test_content_for_returns_nil_when_writing assert ! content_for?(:title) - assert_equal nil, content_for(:title, 'foo') - assert_equal nil, content_for(:title) { output_buffer << 'bar'; nil } - assert_equal nil, content_for(:title) { output_buffer << " \n "; nil } - assert_equal 'foobar', content_for(:title) - assert_equal nil, content_for(:title, 'foo', flush: true) - assert_equal nil, content_for(:title, flush: true) { output_buffer << 'bar'; nil } - assert_equal nil, content_for(:title, flush: true) { output_buffer << " \n "; nil } - assert_equal 'bar', content_for(:title) + assert_nil content_for(:title, "foo") + assert_nil content_for(:title) { output_buffer << "bar"; nil } + assert_nil content_for(:title) { output_buffer << " \n "; nil } + assert_equal "foobar", content_for(:title) + assert_nil content_for(:title, "foo", flush: true) + assert_nil content_for(:title, flush: true) { output_buffer << "bar"; nil } + assert_nil content_for(:title, flush: true) { output_buffer << " \n "; nil } + assert_equal "bar", content_for(:title) end def test_content_for_returns_nil_when_content_missing - assert_equal nil, content_for(:some_missing_key) + assert_nil content_for(:some_missing_key) end def test_content_for_question_mark assert ! content_for?(:title) - content_for :title, 'title' + content_for :title, "title" assert content_for?(:title) assert ! content_for?(:something_else) end @@ -151,12 +153,12 @@ class CaptureHelperTest < ActionView::TestCase def test_content_for_should_be_html_safe_after_flush_empty assert ! content_for?(:title) content_for :title do - content_tag(:p, 'title') + content_tag(:p, "title") end assert content_for(:title).html_safe? content_for :title, "", flush: true content_for(:title) do - content_tag(:p, 'title') + content_tag(:p, "title") end assert content_for(:title).html_safe? end @@ -178,19 +180,19 @@ class CaptureHelperTest < ActionView::TestCase def test_with_output_buffer_swaps_the_output_buffer_given_no_argument assert_nil @av.output_buffer buffer = @av.with_output_buffer do - @av.output_buffer << '.' + @av.output_buffer << "." end - assert_equal '.', buffer + assert_equal ".", buffer assert_nil @av.output_buffer end def test_with_output_buffer_swaps_the_output_buffer_with_an_argument assert_nil @av.output_buffer - buffer = ActionView::OutputBuffer.new('.') + buffer = ActionView::OutputBuffer.new(".") @av.with_output_buffer(buffer) do - @av.output_buffer << '.' + @av.output_buffer << "." end - assert_equal '..', buffer + assert_equal "..", buffer assert_nil @av.output_buffer end @@ -198,7 +200,7 @@ class CaptureHelperTest < ActionView::TestCase buffer = ActionView::OutputBuffer.new @av.output_buffer = buffer @av.with_output_buffer do - @av.output_buffer << '.' + @av.output_buffer << "." end assert buffer.equal?(@av.output_buffer) end diff --git a/actionview/test/template/compiled_templates_test.rb b/actionview/test/template/compiled_templates_test.rb index f6c1283b92..3cd6448e38 100644 --- a/actionview/test/template/compiled_templates_test.rb +++ b/actionview/test/template/compiled_templates_test.rb @@ -1,4 +1,6 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class CompiledTemplatesTest < ActiveSupport::TestCase teardown do @@ -6,28 +8,61 @@ class CompiledTemplatesTest < ActiveSupport::TestCase end def test_template_with_nil_erb_return - assert_equal "This is nil: \n", render(:template => "test/nil_return") + assert_equal "This is nil: \n", render(template: "test/nil_return") + end + + def test_template_with_ruby_keyword_locals + assert_equal "The class is foo", + render(file: "test/render_file_with_ruby_keyword_locals", locals: { class: "foo" }) + end + + def test_template_with_invalid_identifier_locals + locals = { + foo: "bar", + Foo: "bar", + "d-a-s-h-e-s": "", + "white space": "", + } + assert_equal locals.inspect, render(file: "test/render_file_inspect_local_assigns", locals: locals) + end + + def test_template_with_delegation_reserved_keywords + locals = { + _: "one", + arg: "two", + args: "three", + block: "four", + } + assert_equal "one two three four", render(file: "test/test_template_with_delegation_reserved_keywords", locals: locals) + end + + def test_template_with_unicode_identifier + assert_equal "🎂", render(file: "test/render_file_unicode_local", locals: { 🎃: "🎂" }) + end + + def test_template_with_instance_variable_identifier + assert_equal "bar", render(file: "test/render_file_instance_variable", locals: { "@foo": "bar" }) end def test_template_gets_recompiled_when_using_different_keys_in_local_assigns - assert_equal "one", render(:file => "test/render_file_with_locals_and_default") - assert_equal "two", render(:file => "test/render_file_with_locals_and_default", :locals => { :secret => "two" }) + assert_equal "one", render(file: "test/render_file_with_locals_and_default") + assert_equal "two", render(file: "test/render_file_with_locals_and_default", locals: { secret: "two" }) end def test_template_changes_are_not_reflected_with_cached_templates - assert_equal "Hello world!", render(:file => "test/hello_world") + assert_equal "Hello world!", render(file: "test/hello_world") modify_template "test/hello_world.erb", "Goodbye world!" do - assert_equal "Hello world!", render(:file => "test/hello_world") + assert_equal "Hello world!", render(file: "test/hello_world") end - assert_equal "Hello world!", render(:file => "test/hello_world") + assert_equal "Hello world!", render(file: "test/hello_world") end def test_template_changes_are_reflected_with_uncached_templates - assert_equal "Hello world!", render_without_cache(:file => "test/hello_world") + assert_equal "Hello world!", render_without_cache(file: "test/hello_world") modify_template "test/hello_world.erb", "Goodbye world!" do - assert_equal "Goodbye world!", render_without_cache(:file => "test/hello_world") + assert_equal "Goodbye world!", render_without_cache(file: "test/hello_world") end - assert_equal "Hello world!", render_without_cache(:file => "test/hello_world") + assert_equal "Hello world!", render_without_cache(file: "test/hello_world") end private diff --git a/actionview/test/template/controller_helper_test.rb b/actionview/test/template/controller_helper_test.rb index b5e94ea4f1..46d20c188c 100644 --- a/actionview/test/template/controller_helper_test.rb +++ b/actionview/test/template/controller_helper_test.rb @@ -1,4 +1,6 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class ControllerHelperTest < ActionView::TestCase tests ActionView::Helpers::ControllerHelper @@ -9,13 +11,24 @@ class ControllerHelperTest < ActionView::TestCase @controller = OpenStruct.new(default_form_builder: SpecializedFormBuilder) assign_controller(@controller) - assert_equal SpecializedFormBuilder, self.default_form_builder + assert_equal SpecializedFormBuilder, default_form_builder end def test_assign_controller_skips_default_form_builder @controller = OpenStruct.new assign_controller(@controller) - assert_nil self.default_form_builder + assert_nil default_form_builder + end + + def test_respond_to + @controller = OpenStruct.new + assign_controller(@controller) + assert_not respond_to?(:params) + assert respond_to?(:assign_controller) + + @controller.params = {} + assert respond_to?(:params) + assert respond_to?(:assign_controller) end end diff --git a/actionview/test/template/date_helper_i18n_test.rb b/actionview/test/template/date_helper_i18n_test.rb index 52aef56a61..60303b4c91 100644 --- a/actionview/test/template/date_helper_i18n_test.rb +++ b/actionview/test/template/date_helper_i18n_test.rb @@ -1,4 +1,6 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class DateHelperDistanceOfTimeInWordsI18nTests < ActiveSupport::TestCase include ActionView::Helpers::DateHelper @@ -12,24 +14,24 @@ class DateHelperDistanceOfTimeInWordsI18nTests < ActiveSupport::TestCase def test_distance_of_time_in_words_calls_i18n { # with include_seconds - [2.seconds, { :include_seconds => true }] => [:'less_than_x_seconds', 5], - [9.seconds, { :include_seconds => true }] => [:'less_than_x_seconds', 10], - [19.seconds, { :include_seconds => true }] => [:'less_than_x_seconds', 20], - [30.seconds, { :include_seconds => true }] => [:'half_a_minute', nil], - [59.seconds, { :include_seconds => true }] => [:'less_than_x_minutes', 1], - [60.seconds, { :include_seconds => true }] => [:'x_minutes', 1], + [2.seconds, { include_seconds: true }] => [:'less_than_x_seconds', 5], + [9.seconds, { include_seconds: true }] => [:'less_than_x_seconds', 10], + [19.seconds, { include_seconds: true }] => [:'less_than_x_seconds', 20], + [30.seconds, { include_seconds: true }] => [:'half_a_minute', nil], + [59.seconds, { include_seconds: true }] => [:'less_than_x_minutes', 1], + [60.seconds, { include_seconds: true }] => [:'x_minutes', 1], # without include_seconds - [29.seconds, { :include_seconds => false }] => [:'less_than_x_minutes', 1], - [60.seconds, { :include_seconds => false }] => [:'x_minutes', 1], - [44.minutes, { :include_seconds => false }] => [:'x_minutes', 44], - [61.minutes, { :include_seconds => false }] => [:'about_x_hours', 1], - [24.hours, { :include_seconds => false }] => [:'x_days', 1], - [30.days, { :include_seconds => false }] => [:'about_x_months', 1], - [60.days, { :include_seconds => false }] => [:'x_months', 2], - [1.year, { :include_seconds => false }] => [:'about_x_years', 1], - [3.years + 6.months, { :include_seconds => false }] => [:'over_x_years', 3], - [3.years + 10.months, { :include_seconds => false }] => [:'almost_x_years', 4] + [29.seconds, { include_seconds: false }] => [:'less_than_x_minutes', 1], + [60.seconds, { include_seconds: false }] => [:'x_minutes', 1], + [44.minutes, { include_seconds: false }] => [:'x_minutes', 44], + [61.minutes, { include_seconds: false }] => [:'about_x_hours', 1], + [24.hours, { include_seconds: false }] => [:'x_days', 1], + [30.days, { include_seconds: false }] => [:'about_x_months', 1], + [60.days, { include_seconds: false }] => [:'x_months', 2], + [1.year, { include_seconds: false }] => [:'about_x_years', 1], + [3.years + 6.months, { include_seconds: false }] => [:'over_x_years', 3], + [3.years + 10.months, { include_seconds: false }] => [:'almost_x_years', 4] }.each do |passed, expected| assert_distance_of_time_in_words_translates_key passed, expected @@ -46,30 +48,30 @@ class DateHelperDistanceOfTimeInWordsI18nTests < ActiveSupport::TestCase end def test_time_ago_in_words_passes_locale - assert_called_with(I18n, :t, [:less_than_x_minutes, :scope => :'datetime.distance_in_words', :count => 1, :locale => 'ru']) do - time_ago_in_words(15.seconds.ago, :locale => 'ru') + assert_called_with(I18n, :t, [:less_than_x_minutes, scope: :'datetime.distance_in_words', count: 1, locale: "ru"]) do + time_ago_in_words(15.seconds.ago, locale: "ru") end end def test_distance_of_time_pluralizations - { [:'less_than_x_seconds', 1] => 'less than 1 second', - [:'less_than_x_seconds', 2] => 'less than 2 seconds', - [:'less_than_x_minutes', 1] => 'less than a minute', - [:'less_than_x_minutes', 2] => 'less than 2 minutes', - [:'x_minutes', 1] => '1 minute', - [:'x_minutes', 2] => '2 minutes', - [:'about_x_hours', 1] => 'about 1 hour', - [:'about_x_hours', 2] => 'about 2 hours', - [:'x_days', 1] => '1 day', - [:'x_days', 2] => '2 days', - [:'about_x_years', 1] => 'about 1 year', - [:'about_x_years', 2] => 'about 2 years', - [:'over_x_years', 1] => 'over 1 year', - [:'over_x_years', 2] => 'over 2 years' + { [:'less_than_x_seconds', 1] => "less than 1 second", + [:'less_than_x_seconds', 2] => "less than 2 seconds", + [:'less_than_x_minutes', 1] => "less than a minute", + [:'less_than_x_minutes', 2] => "less than 2 minutes", + [:'x_minutes', 1] => "1 minute", + [:'x_minutes', 2] => "2 minutes", + [:'about_x_hours', 1] => "about 1 hour", + [:'about_x_hours', 2] => "about 2 hours", + [:'x_days', 1] => "1 day", + [:'x_days', 2] => "2 days", + [:'about_x_years', 1] => "about 1 year", + [:'about_x_years', 2] => "about 2 years", + [:'over_x_years', 1] => "over 1 year", + [:'over_x_years', 2] => "over 2 years" }.each do |args, expected| key, count = *args - assert_equal expected, I18n.t(key, :count => count, :scope => 'datetime.distance_in_words') + assert_equal expected, I18n.t(key, count: count, scope: "datetime.distance_in_words") end end @@ -78,11 +80,11 @@ class DateHelperDistanceOfTimeInWordsI18nTests < ActiveSupport::TestCase key, count = *expected to = @from + diff - options = { locale: 'en', scope: :'datetime.distance_in_words' }.merge!(expected_options) + options = { locale: "en", scope: :'datetime.distance_in_words' }.merge!(expected_options) options[:count] = count if count assert_called_with(I18n, :t, [key, options]) do - distance_of_time_in_words(@from, to, passed_options.merge(locale: 'en')) + distance_of_time_in_words(@from, to, passed_options.merge(locale: "en")) end end end @@ -95,28 +97,28 @@ class DateHelperSelectTagsI18nTests < ActiveSupport::TestCase def test_select_month_given_use_month_names_option_does_not_translate_monthnames assert_not_called(I18n, :translate) do - select_month(8, :locale => 'en', :use_month_names => Date::MONTHNAMES) + select_month(8, locale: "en", use_month_names: Date::MONTHNAMES) end end def test_select_month_translates_monthnames - assert_called_with(I18n, :translate, [:'date.month_names', :locale => 'en'], returns: Date::MONTHNAMES) do - select_month(8, :locale => 'en') + assert_called_with(I18n, :translate, [:'date.month_names', locale: "en"], returns: Date::MONTHNAMES) do + select_month(8, locale: "en") end end def test_select_month_given_use_short_month_option_translates_abbr_monthnames - assert_called_with(I18n, :translate, [:'date.abbr_month_names', :locale => 'en'], returns: Date::ABBR_MONTHNAMES) do - select_month(8, :locale => 'en', :use_short_month => true) + assert_called_with(I18n, :translate, [:'date.abbr_month_names', locale: "en"], returns: Date::ABBR_MONTHNAMES) do + select_month(8, locale: "en", use_short_month: true) end end def test_date_or_time_select_translates_prompts - prompt_defaults = {:year => 'Year', :month => 'Month', :day => 'Day', :hour => 'Hour', :minute => 'Minute', :second => 'Seconds'} - defaults = {[:'date.order', :locale => 'en', :default => []] => %w(year month day)} + prompt_defaults = { year: "Year", month: "Month", day: "Day", hour: "Hour", minute: "Minute", second: "Seconds" } + defaults = { [:'date.order', locale: "en", default: []] => %w(year month day) } prompt_defaults.each do |key, prompt| - defaults[[('datetime.prompts.' + key.to_s).to_sym, :locale => 'en']] = prompt + defaults[[("datetime.prompts." + key.to_s).to_sym, locale: "en"]] = prompt end prompts_check = -> (prompt, x) do @@ -129,7 +131,7 @@ class DateHelperSelectTagsI18nTests < ActiveSupport::TestCase end I18n.stub(:translate, prompts_check) do - datetime_select('post', 'updated_at', :locale => 'en', :include_seconds => true, :prompt => true, :use_month_names => Date::MONTHNAMES) + datetime_select("post", "updated_at", locale: "en", include_seconds: true, prompt: true, use_month_names: Date::MONTHNAMES) end assert_equal defaults.count, @prompt_called end @@ -138,27 +140,27 @@ class DateHelperSelectTagsI18nTests < ActiveSupport::TestCase def test_date_or_time_select_given_an_order_options_does_not_translate_order assert_not_called(I18n, :translate) do - datetime_select('post', 'updated_at', :order => [:year, :month, :day], :locale => 'en', :use_month_names => Date::MONTHNAMES) + datetime_select("post", "updated_at", order: [:year, :month, :day], locale: "en", use_month_names: Date::MONTHNAMES) end end def test_date_or_time_select_given_no_order_options_translates_order - assert_called_with(I18n, :translate, [ [:'date.order', :locale => 'en', :default => []], [:"date.month_names", {:locale=>"en"}] ], returns: %w(year month day)) do - datetime_select('post', 'updated_at', :locale => 'en') + assert_called_with(I18n, :translate, [ [:'date.order', locale: "en", default: []], [:"date.month_names", { locale: "en" }] ], returns: %w(year month day)) do + datetime_select("post", "updated_at", locale: "en") end end def test_date_or_time_select_given_invalid_order - assert_called_with(I18n, :translate, [:'date.order', :locale => 'en', :default => []], returns: %w(invalid month day)) do + assert_called_with(I18n, :translate, [:'date.order', locale: "en", default: []], returns: %w(invalid month day)) do assert_raise StandardError do - datetime_select('post', 'updated_at', :locale => 'en') + datetime_select("post", "updated_at", locale: "en") end end end def test_date_or_time_select_given_symbol_keys - assert_called_with(I18n, :translate, [ [:'date.order', :locale => 'en', :default => []], [:"date.month_names", {:locale=>"en"}] ], returns: [:year, :month, :day]) do - datetime_select('post', 'updated_at', :locale => 'en') + assert_called_with(I18n, :translate, [ [:'date.order', locale: "en", default: []], [:"date.month_names", { locale: "en" }] ], returns: [:year, :month, :day]) do + datetime_select("post", "updated_at", locale: "en") end end end diff --git a/actionview/test/template/date_helper_test.rb b/actionview/test/template/date_helper_test.rb index e67d5d0e8c..97cfd754be 100644 --- a/actionview/test/template/date_helper_test.rb +++ b/actionview/test/template/date_helper_test.rb @@ -1,4 +1,6 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class DateHelperTest < ActionView::TestCase tests ActionView::Helpers::DateHelper @@ -13,41 +15,41 @@ class DateHelperTest < ActionView::TestCase 123 end def to_param - '123' + "123" end end end - def assert_distance_of_time_in_words(from, to=nil) + def assert_distance_of_time_in_words(from, to = nil) to ||= from # 0..1 minute with :include_seconds => true - assert_equal "less than 5 seconds", distance_of_time_in_words(from, to + 0.seconds, :include_seconds => true) - assert_equal "less than 5 seconds", distance_of_time_in_words(from, to + 4.seconds, :include_seconds => true) - assert_equal "less than 10 seconds", distance_of_time_in_words(from, to + 5.seconds, :include_seconds => true) - assert_equal "less than 10 seconds", distance_of_time_in_words(from, to + 9.seconds, :include_seconds => true) - assert_equal "less than 20 seconds", distance_of_time_in_words(from, to + 10.seconds, :include_seconds => true) - assert_equal "less than 20 seconds", distance_of_time_in_words(from, to + 19.seconds, :include_seconds => true) - assert_equal "half a minute", distance_of_time_in_words(from, to + 20.seconds, :include_seconds => true) - assert_equal "half a minute", distance_of_time_in_words(from, to + 39.seconds, :include_seconds => true) - assert_equal "less than a minute", distance_of_time_in_words(from, to + 40.seconds, :include_seconds => true) - assert_equal "less than a minute", distance_of_time_in_words(from, to + 59.seconds, :include_seconds => true) - assert_equal "1 minute", distance_of_time_in_words(from, to + 60.seconds, :include_seconds => true) - assert_equal "1 minute", distance_of_time_in_words(from, to + 89.seconds, :include_seconds => true) + assert_equal "less than 5 seconds", distance_of_time_in_words(from, to + 0.seconds, include_seconds: true) + assert_equal "less than 5 seconds", distance_of_time_in_words(from, to + 4.seconds, include_seconds: true) + assert_equal "less than 10 seconds", distance_of_time_in_words(from, to + 5.seconds, include_seconds: true) + assert_equal "less than 10 seconds", distance_of_time_in_words(from, to + 9.seconds, include_seconds: true) + assert_equal "less than 20 seconds", distance_of_time_in_words(from, to + 10.seconds, include_seconds: true) + assert_equal "less than 20 seconds", distance_of_time_in_words(from, to + 19.seconds, include_seconds: true) + assert_equal "half a minute", distance_of_time_in_words(from, to + 20.seconds, include_seconds: true) + assert_equal "half a minute", distance_of_time_in_words(from, to + 39.seconds, include_seconds: true) + assert_equal "less than a minute", distance_of_time_in_words(from, to + 40.seconds, include_seconds: true) + assert_equal "less than a minute", distance_of_time_in_words(from, to + 59.seconds, include_seconds: true) + assert_equal "1 minute", distance_of_time_in_words(from, to + 60.seconds, include_seconds: true) + assert_equal "1 minute", distance_of_time_in_words(from, to + 89.seconds, include_seconds: true) # 0..1 minute with :include_seconds => false - assert_equal "less than a minute", distance_of_time_in_words(from, to + 0.seconds, :include_seconds => false) - assert_equal "less than a minute", distance_of_time_in_words(from, to + 4.seconds, :include_seconds => false) - assert_equal "less than a minute", distance_of_time_in_words(from, to + 5.seconds, :include_seconds => false) - assert_equal "less than a minute", distance_of_time_in_words(from, to + 9.seconds, :include_seconds => false) - assert_equal "less than a minute", distance_of_time_in_words(from, to + 10.seconds, :include_seconds => false) - assert_equal "less than a minute", distance_of_time_in_words(from, to + 19.seconds, :include_seconds => false) - assert_equal "less than a minute", distance_of_time_in_words(from, to + 20.seconds, :include_seconds => false) - assert_equal "1 minute", distance_of_time_in_words(from, to + 39.seconds, :include_seconds => false) - assert_equal "1 minute", distance_of_time_in_words(from, to + 40.seconds, :include_seconds => false) - assert_equal "1 minute", distance_of_time_in_words(from, to + 59.seconds, :include_seconds => false) - assert_equal "1 minute", distance_of_time_in_words(from, to + 60.seconds, :include_seconds => false) - assert_equal "1 minute", distance_of_time_in_words(from, to + 89.seconds, :include_seconds => false) + assert_equal "less than a minute", distance_of_time_in_words(from, to + 0.seconds, include_seconds: false) + assert_equal "less than a minute", distance_of_time_in_words(from, to + 4.seconds, include_seconds: false) + assert_equal "less than a minute", distance_of_time_in_words(from, to + 5.seconds, include_seconds: false) + assert_equal "less than a minute", distance_of_time_in_words(from, to + 9.seconds, include_seconds: false) + assert_equal "less than a minute", distance_of_time_in_words(from, to + 10.seconds, include_seconds: false) + assert_equal "less than a minute", distance_of_time_in_words(from, to + 19.seconds, include_seconds: false) + assert_equal "less than a minute", distance_of_time_in_words(from, to + 20.seconds, include_seconds: false) + assert_equal "1 minute", distance_of_time_in_words(from, to + 39.seconds, include_seconds: false) + assert_equal "1 minute", distance_of_time_in_words(from, to + 40.seconds, include_seconds: false) + assert_equal "1 minute", distance_of_time_in_words(from, to + 59.seconds, include_seconds: false) + assert_equal "1 minute", distance_of_time_in_words(from, to + 60.seconds, include_seconds: false) + assert_equal "1 minute", distance_of_time_in_words(from, to + 89.seconds, include_seconds: false) # Note that we are including a 30-second boundary around the interval we # want to test. For instance, "1 minute" is actually 30s to 1m29s. The @@ -119,8 +121,8 @@ class DateHelperTest < ActionView::TestCase # test to < from assert_equal "about 4 hours", distance_of_time_in_words(from + 4.hours, to) - assert_equal "less than 20 seconds", distance_of_time_in_words(from + 19.seconds, to, :include_seconds => true) - assert_equal "less than a minute", distance_of_time_in_words(from + 19.seconds, to, :include_seconds => false) + assert_equal "less than 20 seconds", distance_of_time_in_words(from + 19.seconds, to, include_seconds: true) + assert_equal "less than a minute", distance_of_time_in_words(from + 19.seconds, to, include_seconds: false) end def test_distance_in_words @@ -128,29 +130,47 @@ class DateHelperTest < ActionView::TestCase assert_distance_of_time_in_words(from) end - def test_distance_in_words_with_mathn_required - # test we avoid Integer#/ (redefined by mathn) - silence_warnings { require "mathn" } + def test_distance_in_words_with_nil_input + assert_raises(ArgumentError) { distance_of_time_in_words(nil) } + assert_raises(ArgumentError) { distance_of_time_in_words(0, nil) } + end + + def test_distance_in_words_with_mixed_argument_types + assert_equal "1 minute", distance_of_time_in_words(0, Time.at(60)) + assert_equal "10 minutes", distance_of_time_in_words(Time.at(600), 0) + end + + def test_distance_in_words_doesnt_use_the_quotient_operator + rubinius_skip "Date is written in Ruby and relies on Fixnum#/" + jruby_skip "Date is written in Ruby and relies on Fixnum#/" + + klass = RUBY_VERSION > "2.4" ? Integer : Fixnum + + # Make sure that we avoid {Integer,Fixnum}#/ (redefined by mathn) + klass.send :private, :/ + from = Time.utc(2004, 6, 6, 21, 45, 0) assert_distance_of_time_in_words(from) + ensure + klass.send :public, :/ end def test_time_ago_in_words_passes_include_seconds - assert_equal "less than 20 seconds", time_ago_in_words(15.seconds.ago, :include_seconds => true) - assert_equal "less than a minute", time_ago_in_words(15.seconds.ago, :include_seconds => false) + assert_equal "less than 20 seconds", time_ago_in_words(15.seconds.ago, include_seconds: true) + assert_equal "less than a minute", time_ago_in_words(15.seconds.ago, include_seconds: false) end def test_distance_in_words_with_time_zones from = Time.mktime(2004, 6, 6, 21, 45, 0) - assert_distance_of_time_in_words(from.in_time_zone('Alaska')) - assert_distance_of_time_in_words(from.in_time_zone('Hawaii')) + assert_distance_of_time_in_words(from.in_time_zone("Alaska")) + assert_distance_of_time_in_words(from.in_time_zone("Hawaii")) end def test_distance_in_words_with_different_time_zones from = Time.mktime(2004, 6, 6, 21, 45, 0) assert_distance_of_time_in_words( - from.in_time_zone('Alaska'), - from.in_time_zone('Hawaii') + from.in_time_zone("Alaska"), + from.in_time_zone("Hawaii") ) end @@ -167,9 +187,9 @@ class DateHelperTest < ActionView::TestCase def test_distance_in_words_with_integers assert_equal "1 minute", distance_of_time_in_words(59) - assert_equal "about 1 hour", distance_of_time_in_words(60*60) + assert_equal "about 1 hour", distance_of_time_in_words(60 * 60) assert_equal "1 minute", distance_of_time_in_words(0, 59) - assert_equal "about 1 hour", distance_of_time_in_words(60*60, 0) + assert_equal "about 1 hour", distance_of_time_in_words(60 * 60, 0) assert_equal "about 3 years", distance_of_time_in_words(10**8) assert_equal "about 3 years", distance_of_time_in_words(0, 10**8) end @@ -185,10 +205,10 @@ class DateHelperTest < ActionView::TestCase assert_equal "about 1 hour", distance_of_time_in_words(60.minutes) # include seconds - assert_equal "half a minute", distance_of_time_in_words(39.seconds, 0, :include_seconds => true) - assert_equal "less than a minute", distance_of_time_in_words(40.seconds, 0, :include_seconds => true) - assert_equal "less than a minute", distance_of_time_in_words(59.seconds, 0, :include_seconds => true) - assert_equal "1 minute", distance_of_time_in_words(60.seconds, 0, :include_seconds => true) + assert_equal "half a minute", distance_of_time_in_words(39.seconds, 0, include_seconds: true) + assert_equal "less than a minute", distance_of_time_in_words(40.seconds, 0, include_seconds: true) + assert_equal "less than a minute", distance_of_time_in_words(59.seconds, 0, include_seconds: true) + assert_equal "1 minute", distance_of_time_in_words(60.seconds, 0, include_seconds: true) end def test_time_ago_in_words @@ -196,7 +216,7 @@ class DateHelperTest < ActionView::TestCase end def test_select_day - expected = %(<select id="date_day" name="date[day]">\n) + expected = %(<select id="date_day" name="date[day]">\n).dup expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" @@ -205,58 +225,58 @@ class DateHelperTest < ActionView::TestCase end def test_select_day_with_blank - expected = %(<select id="date_day" name="date[day]">\n) + expected = %(<select id="date_day" name="date[day]">\n).dup expected << %(<option value=""></option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_day(Time.mktime(2003, 8, 16), :include_blank => true) - assert_dom_equal expected, select_day(16, :include_blank => true) + assert_dom_equal expected, select_day(Time.mktime(2003, 8, 16), include_blank: true) + assert_dom_equal expected, select_day(16, include_blank: true) end def test_select_day_nil_with_blank - expected = %(<select id="date_day" name="date[day]">\n) + expected = %(<select id="date_day" name="date[day]">\n).dup expected << %(<option value=""></option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_day(nil, :include_blank => true) + assert_dom_equal expected, select_day(nil, include_blank: true) end def test_select_day_with_two_digit_numbers - expected = %(<select id="date_day" name="date[day]">\n) + expected = %(<select id="date_day" name="date[day]">\n).dup expected << %(<option value="1">01</option>\n<option selected="selected" value="2">02</option>\n<option value="3">03</option>\n<option value="4">04</option>\n<option value="5">05</option>\n<option value="6">06</option>\n<option value="7">07</option>\n<option value="8">08</option>\n<option value="9">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_day(Time.mktime(2011, 8, 2), :use_two_digit_numbers => true) - assert_dom_equal expected, select_day(2, :use_two_digit_numbers => true) + assert_dom_equal expected, select_day(Time.mktime(2011, 8, 2), use_two_digit_numbers: true) + assert_dom_equal expected, select_day(2, use_two_digit_numbers: true) end def test_select_day_with_html_options - expected = %(<select id="date_day" name="date[day]" class="selector">\n) + expected = %(<select id="date_day" name="date[day]" class="selector">\n).dup expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_day(Time.mktime(2003, 8, 16), {}, :class => 'selector') - assert_dom_equal expected, select_day(16, {}, :class => 'selector') + assert_dom_equal expected, select_day(Time.mktime(2003, 8, 16), {}, { class: "selector" }) + assert_dom_equal expected, select_day(16, {}, { class: "selector" }) end def test_select_day_with_default_prompt - expected = %(<select id="date_day" name="date[day]">\n) + expected = %(<select id="date_day" name="date[day]">\n).dup expected << %(<option value="">Day</option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_day(16, :prompt => true) + assert_dom_equal expected, select_day(16, prompt: true) end def test_select_day_with_custom_prompt - expected = %(<select id="date_day" name="date[day]">\n) + expected = %(<select id="date_day" name="date[day]">\n).dup expected << %(<option value="">Choose day</option>\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_day(16, :prompt => 'Choose day') + assert_dom_equal expected, select_day(16, prompt: "Choose day") end def test_select_day_with_generic_with_css_classes - expected = %(<select id="date_day" name="date[day]" class="day">\n) + expected = %(<select id="date_day" name="date[day]" class="day">\n).dup expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" @@ -264,15 +284,15 @@ class DateHelperTest < ActionView::TestCase end def test_select_day_with_custom_with_css_classes - expected = %(<select id="date_day" name="date[day]" class="my-day">\n) + expected = %(<select id="date_day" name="date[day]" class="my-day">\n).dup expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_day(16, with_css_classes: { day: 'my-day' }) + assert_dom_equal expected, select_day(16, with_css_classes: { day: "my-day" }) end def test_select_month - expected = %(<select id="date_month" name="date[month]">\n) + expected = %(<select id="date_month" name="date[month]">\n).dup expected << %(<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n) expected << "</select>\n" @@ -281,151 +301,151 @@ class DateHelperTest < ActionView::TestCase end def test_select_month_with_two_digit_numbers - expected = %(<select id="date_month" name="date[month]">\n) + expected = %(<select id="date_month" name="date[month]">\n).dup expected << %(<option value="1">01</option>\n<option value="2">02</option>\n<option value="3">03</option>\n<option value="4">04</option>\n<option value="5">05</option>\n<option value="6">06</option>\n<option value="7">07</option>\n<option value="8" selected="selected">08</option>\n<option value="9">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_month(Time.mktime(2011, 8, 16), :use_two_digit_numbers => true) - assert_dom_equal expected, select_month(8, :use_two_digit_numbers => true) + assert_dom_equal expected, select_month(Time.mktime(2011, 8, 16), use_two_digit_numbers: true) + assert_dom_equal expected, select_month(8, use_two_digit_numbers: true) end def test_select_month_with_disabled - expected = %(<select id="date_month" name="date[month]" disabled="disabled">\n) + expected = %(<select id="date_month" name="date[month]" disabled="disabled">\n).dup expected << %(<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), :disabled => true) - assert_dom_equal expected, select_month(8, :disabled => true) + assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), disabled: true) + assert_dom_equal expected, select_month(8, disabled: true) end def test_select_month_with_field_name_override - expected = %(<select id="date_mois" name="date[mois]">\n) + expected = %(<select id="date_mois" name="date[mois]">\n).dup expected << %(<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), :field_name => 'mois') - assert_dom_equal expected, select_month(8, :field_name => 'mois') + assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), field_name: "mois") + assert_dom_equal expected, select_month(8, field_name: "mois") end def test_select_month_with_blank - expected = %(<select id="date_month" name="date[month]">\n) + expected = %(<select id="date_month" name="date[month]">\n).dup expected << %(<option value=""></option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), :include_blank => true) - assert_dom_equal expected, select_month(8, :include_blank => true) + assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), include_blank: true) + assert_dom_equal expected, select_month(8, include_blank: true) end def test_select_month_nil_with_blank - expected = %(<select id="date_month" name="date[month]">\n) + expected = %(<select id="date_month" name="date[month]">\n).dup expected << %(<option value=""></option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_month(nil, :include_blank => true) + assert_dom_equal expected, select_month(nil, include_blank: true) end def test_select_month_with_numbers - expected = %(<select id="date_month" name="date[month]">\n) + expected = %(<select id="date_month" name="date[month]">\n).dup expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8" selected="selected">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), :use_month_numbers => true) - assert_dom_equal expected, select_month(8, :use_month_numbers => true) + assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), use_month_numbers: true) + assert_dom_equal expected, select_month(8, use_month_numbers: true) end def test_select_month_with_numbers_and_names - expected = %(<select id="date_month" name="date[month]">\n) + expected = %(<select id="date_month" name="date[month]">\n).dup expected << %(<option value="1">1 - January</option>\n<option value="2">2 - February</option>\n<option value="3">3 - March</option>\n<option value="4">4 - April</option>\n<option value="5">5 - May</option>\n<option value="6">6 - June</option>\n<option value="7">7 - July</option>\n<option value="8" selected="selected">8 - August</option>\n<option value="9">9 - September</option>\n<option value="10">10 - October</option>\n<option value="11">11 - November</option>\n<option value="12">12 - December</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), :add_month_numbers => true) - assert_dom_equal expected, select_month(8, :add_month_numbers => true) + assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), add_month_numbers: true) + assert_dom_equal expected, select_month(8, add_month_numbers: true) end def test_select_month_with_format_string - expected = %(<select id="date_month" name="date[month]">\n) + expected = %(<select id="date_month" name="date[month]">\n).dup expected << %(<option value="1">January (01)</option>\n<option value="2">February (02)</option>\n<option value="3">March (03)</option>\n<option value="4">April (04)</option>\n<option value="5">May (05)</option>\n<option value="6">June (06)</option>\n<option value="7">July (07)</option>\n<option value="8" selected="selected">August (08)</option>\n<option value="9">September (09)</option>\n<option value="10">October (10)</option>\n<option value="11">November (11)</option>\n<option value="12">December (12)</option>\n) expected << "</select>\n" - format_string = '%{name} (%<number>02d)' - assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), :month_format_string => format_string) - assert_dom_equal expected, select_month(8, :month_format_string => format_string) + format_string = "%{name} (%<number>02d)" + assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), month_format_string: format_string) + assert_dom_equal expected, select_month(8, month_format_string: format_string) end def test_select_month_with_numbers_and_names_with_abbv - expected = %(<select id="date_month" name="date[month]">\n) + expected = %(<select id="date_month" name="date[month]">\n).dup expected << %(<option value="1">1 - Jan</option>\n<option value="2">2 - Feb</option>\n<option value="3">3 - Mar</option>\n<option value="4">4 - Apr</option>\n<option value="5">5 - May</option>\n<option value="6">6 - Jun</option>\n<option value="7">7 - Jul</option>\n<option value="8" selected="selected">8 - Aug</option>\n<option value="9">9 - Sep</option>\n<option value="10">10 - Oct</option>\n<option value="11">11 - Nov</option>\n<option value="12">12 - Dec</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), :add_month_numbers => true, :use_short_month => true) - assert_dom_equal expected, select_month(8, :add_month_numbers => true, :use_short_month => true) + assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), add_month_numbers: true, use_short_month: true) + assert_dom_equal expected, select_month(8, add_month_numbers: true, use_short_month: true) end def test_select_month_with_abbv - expected = %(<select id="date_month" name="date[month]">\n) + expected = %(<select id="date_month" name="date[month]">\n).dup expected << %(<option value="1">Jan</option>\n<option value="2">Feb</option>\n<option value="3">Mar</option>\n<option value="4">Apr</option>\n<option value="5">May</option>\n<option value="6">Jun</option>\n<option value="7">Jul</option>\n<option value="8" selected="selected">Aug</option>\n<option value="9">Sep</option>\n<option value="10">Oct</option>\n<option value="11">Nov</option>\n<option value="12">Dec</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), :use_short_month => true) - assert_dom_equal expected, select_month(8, :use_short_month => true) + assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), use_short_month: true) + assert_dom_equal expected, select_month(8, use_short_month: true) end def test_select_month_with_custom_names month_names = %w(nil Januar Februar Marts April Maj Juni Juli August September Oktober November December) - expected = %(<select id="date_month" name="date[month]">\n) + expected = %(<select id="date_month" name="date[month]">\n).dup 1.upto(12) { |month| expected << %(<option value="#{month}"#{' selected="selected"' if month == 8}>#{month_names[month]}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), :use_month_names => month_names) - assert_dom_equal expected, select_month(8, :use_month_names => month_names) + assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), use_month_names: month_names) + assert_dom_equal expected, select_month(8, use_month_names: month_names) end def test_select_month_with_zero_indexed_custom_names month_names = %w(Januar Februar Marts April Maj Juni Juli August September Oktober November December) - expected = %(<select id="date_month" name="date[month]">\n) - 1.upto(12) { |month| expected << %(<option value="#{month}"#{' selected="selected"' if month == 8}>#{month_names[month-1]}</option>\n) } + expected = %(<select id="date_month" name="date[month]">\n).dup + 1.upto(12) { |month| expected << %(<option value="#{month}"#{' selected="selected"' if month == 8}>#{month_names[month - 1]}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), :use_month_names => month_names) - assert_dom_equal expected, select_month(8, :use_month_names => month_names) + assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), use_month_names: month_names) + assert_dom_equal expected, select_month(8, use_month_names: month_names) end def test_select_month_with_hidden - assert_dom_equal "<input type=\"hidden\" id=\"date_month\" name=\"date[month]\" value=\"8\" />\n", select_month(8, :use_hidden => true) + assert_dom_equal "<input type=\"hidden\" id=\"date_month\" name=\"date[month]\" value=\"8\" />\n", select_month(8, use_hidden: true) end def test_select_month_with_hidden_and_field_name - assert_dom_equal "<input type=\"hidden\" id=\"date_mois\" name=\"date[mois]\" value=\"8\" />\n", select_month(8, :use_hidden => true, :field_name => 'mois') + assert_dom_equal "<input type=\"hidden\" id=\"date_mois\" name=\"date[mois]\" value=\"8\" />\n", select_month(8, use_hidden: true, field_name: "mois") end def test_select_month_with_html_options - expected = %(<select id="date_month" name="date[month]" class="selector" accesskey="M">\n) + expected = %(<select id="date_month" name="date[month]" class="selector" accesskey="M">\n).dup expected << %(<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), {}, :class => 'selector', :accesskey => 'M') + assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), {}, { class: "selector", accesskey: "M" }) end def test_select_month_with_default_prompt - expected = %(<select id="date_month" name="date[month]">\n) + expected = %(<select id="date_month" name="date[month]">\n).dup expected << %(<option value="">Month</option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_month(8, :prompt => true) + assert_dom_equal expected, select_month(8, prompt: true) end def test_select_month_with_custom_prompt - expected = %(<select id="date_month" name="date[month]">\n) + expected = %(<select id="date_month" name="date[month]">\n).dup expected << %(<option value="">Choose month</option>\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_month(8, :prompt => 'Choose month') + assert_dom_equal expected, select_month(8, prompt: "Choose month") end def test_select_month_with_generic_with_css_classes - expected = %(<select id="date_month" name="date[month]" class="month">\n) + expected = %(<select id="date_month" name="date[month]" class="month">\n).dup expected << %(<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n) expected << "</select>\n" @@ -433,94 +453,94 @@ class DateHelperTest < ActionView::TestCase end def test_select_month_with_custom_with_css_classes - expected = %(<select id="date_month" name="date[month]" class="my-month">\n) + expected = %(<select id="date_month" name="date[month]" class="my-month">\n).dup expected << %(<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_month(8, with_css_classes: { month: 'my-month' }) + assert_dom_equal expected, select_month(8, with_css_classes: { month: "my-month" }) end def test_select_year - expected = %(<select id="date_year" name="date[year]">\n) + expected = %(<select id="date_year" name="date[year]">\n).dup expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_year(Time.mktime(2003, 8, 16), :start_year => 2003, :end_year => 2005) - assert_dom_equal expected, select_year(2003, :start_year => 2003, :end_year => 2005) + assert_dom_equal expected, select_year(Time.mktime(2003, 8, 16), start_year: 2003, end_year: 2005) + assert_dom_equal expected, select_year(2003, start_year: 2003, end_year: 2005) end def test_select_year_with_disabled - expected = %(<select id="date_year" name="date[year]" disabled="disabled">\n) + expected = %(<select id="date_year" name="date[year]" disabled="disabled">\n).dup expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_year(Time.mktime(2003, 8, 16), :disabled => true, :start_year => 2003, :end_year => 2005) - assert_dom_equal expected, select_year(2003, :disabled => true, :start_year => 2003, :end_year => 2005) + assert_dom_equal expected, select_year(Time.mktime(2003, 8, 16), disabled: true, start_year: 2003, end_year: 2005) + assert_dom_equal expected, select_year(2003, disabled: true, start_year: 2003, end_year: 2005) end def test_select_year_with_field_name_override - expected = %(<select id="date_annee" name="date[annee]">\n) + expected = %(<select id="date_annee" name="date[annee]">\n).dup expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_year(Time.mktime(2003, 8, 16), :start_year => 2003, :end_year => 2005, :field_name => 'annee') - assert_dom_equal expected, select_year(2003, :start_year => 2003, :end_year => 2005, :field_name => 'annee') + assert_dom_equal expected, select_year(Time.mktime(2003, 8, 16), start_year: 2003, end_year: 2005, field_name: "annee") + assert_dom_equal expected, select_year(2003, start_year: 2003, end_year: 2005, field_name: "annee") end def test_select_year_with_type_discarding - expected = %(<select id="date_year" name="date_year">\n) + expected = %(<select id="date_year" name="date_year">\n).dup expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" assert_dom_equal expected, select_year( - Time.mktime(2003, 8, 16), :prefix => "date_year", :discard_type => true, :start_year => 2003, :end_year => 2005) + Time.mktime(2003, 8, 16), prefix: "date_year", discard_type: true, start_year: 2003, end_year: 2005) assert_dom_equal expected, select_year( - 2003, :prefix => "date_year", :discard_type => true, :start_year => 2003, :end_year => 2005) + 2003, prefix: "date_year", discard_type: true, start_year: 2003, end_year: 2005) end def test_select_year_descending - expected = %(<select id="date_year" name="date[year]">\n) + expected = %(<select id="date_year" name="date[year]">\n).dup expected << %(<option value="2005" selected="selected">2005</option>\n<option value="2004">2004</option>\n<option value="2003">2003</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_year(Time.mktime(2005, 8, 16), :start_year => 2005, :end_year => 2003) - assert_dom_equal expected, select_year(2005, :start_year => 2005, :end_year => 2003) + assert_dom_equal expected, select_year(Time.mktime(2005, 8, 16), start_year: 2005, end_year: 2003) + assert_dom_equal expected, select_year(2005, start_year: 2005, end_year: 2003) end def test_select_year_with_hidden - assert_dom_equal "<input type=\"hidden\" id=\"date_year\" name=\"date[year]\" value=\"2007\" />\n", select_year(2007, :use_hidden => true) + assert_dom_equal "<input type=\"hidden\" id=\"date_year\" name=\"date[year]\" value=\"2007\" />\n", select_year(2007, use_hidden: true) end def test_select_year_with_hidden_and_field_name - assert_dom_equal "<input type=\"hidden\" id=\"date_anno\" name=\"date[anno]\" value=\"2007\" />\n", select_year(2007, :use_hidden => true, :field_name => 'anno') + assert_dom_equal "<input type=\"hidden\" id=\"date_anno\" name=\"date[anno]\" value=\"2007\" />\n", select_year(2007, use_hidden: true, field_name: "anno") end def test_select_year_with_html_options - expected = %(<select id="date_year" name="date[year]" class="selector" accesskey="M">\n) + expected = %(<select id="date_year" name="date[year]" class="selector" accesskey="M">\n).dup expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_year(Time.mktime(2003, 8, 16), {:start_year => 2003, :end_year => 2005}, :class => 'selector', :accesskey => 'M') + assert_dom_equal expected, select_year(Time.mktime(2003, 8, 16), { start_year: 2003, end_year: 2005 }, { class: "selector", accesskey: "M" }) end def test_select_year_with_default_prompt - expected = %(<select id="date_year" name="date[year]">\n) + expected = %(<select id="date_year" name="date[year]">\n).dup expected << %(<option value="">Year</option>\n<option value="2003">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_year(nil, :start_year => 2003, :end_year => 2005, :prompt => true) + assert_dom_equal expected, select_year(nil, start_year: 2003, end_year: 2005, prompt: true) end def test_select_year_with_custom_prompt - expected = %(<select id="date_year" name="date[year]">\n) + expected = %(<select id="date_year" name="date[year]">\n).dup expected << %(<option value="">Choose year</option>\n<option value="2003">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_year(nil, :start_year => 2003, :end_year => 2005, :prompt => 'Choose year') + assert_dom_equal expected, select_year(nil, start_year: 2003, end_year: 2005, prompt: "Choose year") end def test_select_year_with_generic_with_css_classes - expected = %(<select id="date_year" name="date[year]" class="year">\n) + expected = %(<select id="date_year" name="date[year]" class="year">\n).dup expected << %(<option value="2003">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" @@ -528,15 +548,22 @@ class DateHelperTest < ActionView::TestCase end def test_select_year_with_custom_with_css_classes - expected = %(<select id="date_year" name="date[year]" class="my-year">\n) + expected = %(<select id="date_year" name="date[year]" class="my-year">\n).dup expected << %(<option value="2003">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_year(nil, start_year: 2003, end_year: 2005, with_css_classes: { year: 'my-year' }) + assert_dom_equal expected, select_year(nil, start_year: 2003, end_year: 2005, with_css_classes: { year: "my-year" }) + end + + def test_select_year_with_position + expected = %(<select id="date_year_1i" name="date[year(1i)]">\n).dup + expected << %(<option value="2003">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) + expected << "</select>\n" + assert_dom_equal expected, select_year(Date.current, include_position: true, start_year: 2003, end_year: 2005) end def test_select_hour - expected = %(<select id="date_hour" name="date[hour]">\n) + expected = %(<select id="date_hour" name="date[hour]">\n).dup expected << %(<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" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n) expected << "</select>\n" @@ -544,71 +571,71 @@ class DateHelperTest < ActionView::TestCase end def test_select_hour_with_ampm - expected = %(<select id="date_hour" name="date[hour]">\n) + expected = %(<select id="date_hour" name="date[hour]">\n).dup expected << %(<option value="00">12 AM</option>\n<option value="01">01 AM</option>\n<option value="02">02 AM</option>\n<option value="03">03 AM</option>\n<option value="04">04 AM</option>\n<option value="05">05 AM</option>\n<option value="06">06 AM</option>\n<option value="07">07 AM</option>\n<option value="08" selected="selected">08 AM</option>\n<option value="09">09 AM</option>\n<option value="10">10 AM</option>\n<option value="11">11 AM</option>\n<option value="12">12 PM</option>\n<option value="13">01 PM</option>\n<option value="14">02 PM</option>\n<option value="15">03 PM</option>\n<option value="16">04 PM</option>\n<option value="17">05 PM</option>\n<option value="18">06 PM</option>\n<option value="19">07 PM</option>\n<option value="20">08 PM</option>\n<option value="21">09 PM</option>\n<option value="22">10 PM</option>\n<option value="23">11 PM</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18), :ampm => true) + assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18), ampm: true) end def test_select_hour_with_disabled - expected = %(<select id="date_hour" name="date[hour]" disabled="disabled">\n) + expected = %(<select id="date_hour" name="date[hour]" disabled="disabled">\n).dup expected << %(<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" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18), :disabled => true) + assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18), disabled: true) end def test_select_hour_with_field_name_override - expected = %(<select id="date_heure" name="date[heure]">\n) + expected = %(<select id="date_heure" name="date[heure]">\n).dup expected << %(<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" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18), :field_name => 'heure') + assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18), field_name: "heure") end def test_select_hour_with_blank - expected = %(<select id="date_hour" name="date[hour]">\n) + expected = %(<select id="date_hour" name="date[hour]">\n).dup expected << %(<option value=""></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" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18), :include_blank => true) + assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18), include_blank: true) end def test_select_hour_nil_with_blank - expected = %(<select id="date_hour" name="date[hour]">\n) + expected = %(<select id="date_hour" name="date[hour]">\n).dup expected << %(<option value=""></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">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) expected << "</select>\n" - assert_dom_equal expected, select_hour(nil, :include_blank => true) + assert_dom_equal expected, select_hour(nil, include_blank: true) end def test_select_hour_with_html_options - expected = %(<select id="date_hour" name="date[hour]" class="selector" accesskey="M">\n) + expected = %(<select id="date_hour" name="date[hour]" class="selector" accesskey="M">\n).dup expected << %(<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" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18), {}, :class => 'selector', :accesskey => 'M') + assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18), {}, { class: "selector", accesskey: "M" }) end def test_select_hour_with_default_prompt - expected = %(<select id="date_hour" name="date[hour]">\n) + expected = %(<select id="date_hour" name="date[hour]">\n).dup expected << %(<option value="">Hour</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" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18), :prompt => true) + assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18), prompt: true) end def test_select_hour_with_custom_prompt - expected = %(<select id="date_hour" name="date[hour]">\n) + expected = %(<select id="date_hour" name="date[hour]">\n).dup expected << %(<option value="">Choose hour</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" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18), :prompt => 'Choose hour') + assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18), prompt: "Choose hour") end def test_select_hour_with_generic_with_css_classes - expected = %(<select id="date_hour" name="date[hour]" class="hour">\n) + expected = %(<select id="date_hour" name="date[hour]" class="hour">\n).dup expected << %(<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" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n) expected << "</select>\n" @@ -616,15 +643,15 @@ class DateHelperTest < ActionView::TestCase end def test_select_hour_with_custom_with_css_classes - expected = %(<select id="date_hour" name="date[hour]" class="my-hour">\n) + expected = %(<select id="date_hour" name="date[hour]" class="my-hour">\n).dup expected << %(<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" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18), with_css_classes: { hour: 'my-hour' }) + assert_dom_equal expected, select_hour(Time.mktime(2003, 8, 16, 8, 4, 18), with_css_classes: { hour: "my-hour" }) end def test_select_minute - expected = %(<select id="date_minute" name="date[minute]">\n) + expected = %(<select id="date_minute" name="date[minute]">\n).dup expected << %(<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" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<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" @@ -632,87 +659,87 @@ class DateHelperTest < ActionView::TestCase end def test_select_minute_with_disabled - expected = %(<select id="date_minute" name="date[minute]" disabled="disabled">\n) + expected = %(<select id="date_minute" name="date[minute]" disabled="disabled">\n).dup expected << %(<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" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<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_minute(Time.mktime(2003, 8, 16, 8, 4, 18), :disabled => true) + assert_dom_equal expected, select_minute(Time.mktime(2003, 8, 16, 8, 4, 18), disabled: true) end def test_select_minute_with_field_name_override - expected = %(<select id="date_minuto" name="date[minuto]">\n) + expected = %(<select id="date_minuto" name="date[minuto]">\n).dup expected << %(<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" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<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_minute(Time.mktime(2003, 8, 16, 8, 4, 18), :field_name => 'minuto') + assert_dom_equal expected, select_minute(Time.mktime(2003, 8, 16, 8, 4, 18), field_name: "minuto") end def test_select_minute_with_blank - expected = %(<select id="date_minute" name="date[minute]">\n) + expected = %(<select id="date_minute" name="date[minute]">\n).dup expected << %(<option value=""></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" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<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_minute(Time.mktime(2003, 8, 16, 8, 4, 18), :include_blank => true) + assert_dom_equal expected, select_minute(Time.mktime(2003, 8, 16, 8, 4, 18), include_blank: true) end def test_select_minute_with_blank_and_step - expected = %(<select id="date_minute" name="date[minute]">\n) + expected = %(<select id="date_minute" name="date[minute]">\n).dup expected << %(<option value=""></option>\n<option value="00">00</option>\n<option value="15">15</option>\n<option value="30">30</option>\n<option value="45">45</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_minute(Time.mktime(2003, 8, 16, 8, 4, 18), { :include_blank => true , :minute_step => 15 }) + assert_dom_equal expected, select_minute(Time.mktime(2003, 8, 16, 8, 4, 18), include_blank: true, minute_step: 15) end def test_select_minute_nil_with_blank - expected = %(<select id="date_minute" name="date[minute]">\n) + expected = %(<select id="date_minute" name="date[minute]">\n).dup expected << %(<option value=""></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">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_minute(nil, :include_blank => true) + assert_dom_equal expected, select_minute(nil, include_blank: true) end def test_select_minute_nil_with_blank_and_step - expected = %(<select id="date_minute" name="date[minute]">\n) + expected = %(<select id="date_minute" name="date[minute]">\n).dup expected << %(<option value=""></option>\n<option value="00">00</option>\n<option value="15">15</option>\n<option value="30">30</option>\n<option value="45">45</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_minute(nil, { :include_blank => true , :minute_step => 15 }) + assert_dom_equal expected, select_minute(nil, include_blank: true, minute_step: 15) end def test_select_minute_with_hidden - assert_dom_equal "<input type=\"hidden\" id=\"date_minute\" name=\"date[minute]\" value=\"8\" />\n", select_minute(8, :use_hidden => true) + assert_dom_equal "<input type=\"hidden\" id=\"date_minute\" name=\"date[minute]\" value=\"8\" />\n", select_minute(8, use_hidden: true) end def test_select_minute_with_hidden_and_field_name - assert_dom_equal "<input type=\"hidden\" id=\"date_minuto\" name=\"date[minuto]\" value=\"8\" />\n", select_minute(8, :use_hidden => true, :field_name => 'minuto') + assert_dom_equal "<input type=\"hidden\" id=\"date_minuto\" name=\"date[minuto]\" value=\"8\" />\n", select_minute(8, use_hidden: true, field_name: "minuto") end def test_select_minute_with_html_options - expected = %(<select id="date_minute" name="date[minute]" class="selector" accesskey="M">\n) + expected = %(<select id="date_minute" name="date[minute]" class="selector" accesskey="M">\n).dup expected << %(<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" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<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_minute(Time.mktime(2003, 8, 16, 8, 4, 18), {}, :class => 'selector', :accesskey => 'M') + assert_dom_equal expected, select_minute(Time.mktime(2003, 8, 16, 8, 4, 18), {}, { class: "selector", accesskey: "M" }) end def test_select_minute_with_default_prompt - expected = %(<select id="date_minute" name="date[minute]">\n) + expected = %(<select id="date_minute" name="date[minute]">\n).dup expected << %(<option value="">Minute</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" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<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_minute(Time.mktime(2003, 8, 16, 8, 4, 18), :prompt => true) + assert_dom_equal expected, select_minute(Time.mktime(2003, 8, 16, 8, 4, 18), prompt: true) end def test_select_minute_with_custom_prompt - expected = %(<select id="date_minute" name="date[minute]">\n) + expected = %(<select id="date_minute" name="date[minute]">\n).dup expected << %(<option value="">Choose minute</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" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<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_minute(Time.mktime(2003, 8, 16, 8, 4, 18), :prompt => 'Choose minute') + assert_dom_equal expected, select_minute(Time.mktime(2003, 8, 16, 8, 4, 18), prompt: "Choose minute") end def test_select_minute_with_generic_with_css_classes - expected = %(<select id="date_minute" name="date[minute]" class="minute">\n) + expected = %(<select id="date_minute" name="date[minute]" class="minute">\n).dup expected << %(<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" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<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" @@ -720,15 +747,15 @@ class DateHelperTest < ActionView::TestCase end def test_select_minute_with_custom_with_css_classes - expected = %(<select id="date_minute" name="date[minute]" class="my-minute">\n) + expected = %(<select id="date_minute" name="date[minute]" class="my-minute">\n).dup expected << %(<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" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<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_minute(Time.mktime(2003, 8, 16, 8, 4, 18), with_css_classes: { minute: 'my-minute' }) + assert_dom_equal expected, select_minute(Time.mktime(2003, 8, 16, 8, 4, 18), with_css_classes: { minute: "my-minute" }) end def test_select_second - expected = %(<select id="date_second" name="date[second]">\n) + expected = %(<select id="date_second" name="date[second]">\n).dup expected << %(<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" @@ -736,63 +763,63 @@ class DateHelperTest < ActionView::TestCase end def test_select_second_with_disabled - expected = %(<select id="date_second" name="date[second]" disabled="disabled">\n) + expected = %(<select id="date_second" name="date[second]" disabled="disabled">\n).dup expected << %(<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_second(Time.mktime(2003, 8, 16, 8, 4, 18), :disabled => true) + assert_dom_equal expected, select_second(Time.mktime(2003, 8, 16, 8, 4, 18), disabled: true) end def test_select_second_with_field_name_override - expected = %(<select id="date_segundo" name="date[segundo]">\n) + expected = %(<select id="date_segundo" name="date[segundo]">\n).dup expected << %(<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_second(Time.mktime(2003, 8, 16, 8, 4, 18), :field_name => 'segundo') + assert_dom_equal expected, select_second(Time.mktime(2003, 8, 16, 8, 4, 18), field_name: "segundo") end def test_select_second_with_blank - expected = %(<select id="date_second" name="date[second]">\n) + expected = %(<select id="date_second" name="date[second]">\n).dup expected << %(<option value=""></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_second(Time.mktime(2003, 8, 16, 8, 4, 18), :include_blank => true) + assert_dom_equal expected, select_second(Time.mktime(2003, 8, 16, 8, 4, 18), include_blank: true) end def test_select_second_nil_with_blank - expected = %(<select id="date_second" name="date[second]">\n) + expected = %(<select id="date_second" name="date[second]">\n).dup expected << %(<option value=""></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">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_second(nil, :include_blank => true) + assert_dom_equal expected, select_second(nil, include_blank: true) end def test_select_second_with_html_options - expected = %(<select id="date_second" name="date[second]" class="selector" accesskey="M">\n) + expected = %(<select id="date_second" name="date[second]" class="selector" accesskey="M">\n).dup expected << %(<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_second(Time.mktime(2003, 8, 16, 8, 4, 18), {}, :class => 'selector', :accesskey => 'M') + assert_dom_equal expected, select_second(Time.mktime(2003, 8, 16, 8, 4, 18), {}, { class: "selector", accesskey: "M" }) end def test_select_second_with_default_prompt - expected = %(<select id="date_second" name="date[second]">\n) + expected = %(<select id="date_second" name="date[second]">\n).dup expected << %(<option value="">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_second(Time.mktime(2003, 8, 16, 8, 4, 18), :prompt => true) + assert_dom_equal expected, select_second(Time.mktime(2003, 8, 16, 8, 4, 18), prompt: true) end def test_select_second_with_custom_prompt - expected = %(<select id="date_second" name="date[second]">\n) + expected = %(<select id="date_second" name="date[second]">\n).dup 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_second(Time.mktime(2003, 8, 16, 8, 4, 18), :prompt => 'Choose seconds') + assert_dom_equal expected, select_second(Time.mktime(2003, 8, 16, 8, 4, 18), prompt: "Choose seconds") end def test_select_second_with_generic_with_css_classes - expected = %(<select id="date_second" name="date[second]" class="second">\n) + expected = %(<select id="date_second" name="date[second]" class="second">\n).dup expected << %(<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" @@ -800,15 +827,15 @@ class DateHelperTest < ActionView::TestCase end def test_select_second_with_custom_with_css_classes - expected = %(<select id="date_second" name="date[second]" class="my-second">\n) + expected = %(<select id="date_second" name="date[second]" class="my-second">\n).dup expected << %(<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_second(Time.mktime(2003, 8, 16, 8, 4, 18), with_css_classes: { second: 'my-second' }) + assert_dom_equal expected, select_second(Time.mktime(2003, 8, 16, 8, 4, 18), with_css_classes: { second: "my-second" }) end def test_select_date - expected = %(<select id="date_first_year" name="date[first][year]">\n) + expected = %(<select id="date_first_year" name="date[first][year]">\n).dup expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" @@ -820,20 +847,20 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), :start_year => 2003, :end_year => 2005, :prefix => "date[first]") + assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), start_year: 2003, end_year: 2005, prefix: "date[first]") end def test_select_date_with_too_big_range_between_start_year_and_end_year - assert_raise(ArgumentError) { select_date(Time.mktime(2003, 8, 16), :start_year => 2000, :end_year => 20000, :prefix => "date[first]", :order => [:month, :day, :year]) } - assert_raise(ArgumentError) { select_date(Time.mktime(2003, 8, 16), :start_year => Date.today.year - 100.years, :end_year => 2000, :prefix => "date[first]", :order => [:month, :day, :year]) } + assert_raise(ArgumentError) { select_date(Time.mktime(2003, 8, 16), start_year: 2000, end_year: 20000, prefix: "date[first]", order: [:month, :day, :year]) } + assert_raise(ArgumentError) { select_date(Time.mktime(2003, 8, 16), start_year: 100, end_year: 2000, prefix: "date[first]", order: [:month, :day, :year]) } end def test_select_date_can_have_more_then_1000_years_interval_if_forced_via_parameter - assert_nothing_raised { select_date(Time.mktime(2003, 8, 16), :start_year => 2000, :end_year => 3100, :max_years_allowed => 2000) } + assert_nothing_raised { select_date(Time.mktime(2003, 8, 16), start_year: 2000, end_year: 3100, max_years_allowed: 2000) } end def test_select_date_with_order - expected = %(<select id="date_first_month" name="date[first][month]">\n) + expected = %(<select id="date_first_month" name="date[first][month]">\n).dup expected << %(<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n) expected << "</select>\n" @@ -841,24 +868,24 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - expected << %(<select id="date_first_year" name="date[first][year]">\n) + expected << %(<select id="date_first_year" name="date[first][year]">\n) expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), :start_year => 2003, :end_year => 2005, :prefix => "date[first]", :order => [:month, :day, :year]) + assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), start_year: 2003, end_year: 2005, prefix: "date[first]", order: [:month, :day, :year]) end def test_select_date_with_incomplete_order # Since the order is incomplete nothing will be shown - expected = %(<input id="date_first_year" name="date[first][year]" type="hidden" value="2003" />\n) + expected = %(<input id="date_first_year" name="date[first][year]" type="hidden" value="2003" />\n).dup expected << %(<input id="date_first_month" name="date[first][month]" type="hidden" value="8" />\n) expected << %(<input id="date_first_day" name="date[first][day]" type="hidden" value="1" />\n) - assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), :start_year => 2003, :end_year => 2005, :prefix => "date[first]", :order => [:day]) + assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), start_year: 2003, end_year: 2005, prefix: "date[first]", order: [:day]) end def test_select_date_with_disabled - expected = %(<select id="date_first_year" name="date[first][year]" disabled="disabled">\n) + expected = %(<select id="date_first_year" name="date[first][year]" disabled="disabled">\n).dup expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" @@ -870,12 +897,12 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), :start_year => 2003, :end_year => 2005, :prefix => "date[first]", :disabled => true) + assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), start_year: 2003, end_year: 2005, prefix: "date[first]", disabled: true) end def test_select_date_with_no_start_year - expected = %(<select id="date_first_year" name="date[first][year]">\n) - (Date.today.year-5).upto(Date.today.year+1) do |y| + expected = %(<select id="date_first_year" name="date[first][year]">\n).dup + (Date.today.year - 5).upto(Date.today.year + 1) do |y| if y == Date.today.year expected << %(<option value="#{y}" selected="selected">#{y}</option>\n) else @@ -893,12 +920,12 @@ class DateHelperTest < ActionView::TestCase expected << "</select>\n" assert_dom_equal expected, select_date( - Time.mktime(Date.today.year, 8, 16), :end_year => Date.today.year+1, :prefix => "date[first]" + Time.mktime(Date.today.year, 8, 16), end_year: Date.today.year + 1, prefix: "date[first]" ) end def test_select_date_with_no_end_year - expected = %(<select id="date_first_year" name="date[first][year]">\n) + expected = %(<select id="date_first_year" name="date[first][year]">\n).dup 2003.upto(2008) do |y| if y == 2003 expected << %(<option value="#{y}" selected="selected">#{y}</option>\n) @@ -917,13 +944,13 @@ class DateHelperTest < ActionView::TestCase expected << "</select>\n" assert_dom_equal expected, select_date( - Time.mktime(2003, 8, 16), :start_year => 2003, :prefix => "date[first]" + Time.mktime(2003, 8, 16), start_year: 2003, prefix: "date[first]" ) end def test_select_date_with_no_start_or_end_year - expected = %(<select id="date_first_year" name="date[first][year]">\n) - (Date.today.year-5).upto(Date.today.year+5) do |y| + expected = %(<select id="date_first_year" name="date[first][year]">\n).dup + (Date.today.year - 5).upto(Date.today.year + 5) do |y| if y == Date.today.year expected << %(<option value="#{y}" selected="selected">#{y}</option>\n) else @@ -941,12 +968,12 @@ class DateHelperTest < ActionView::TestCase expected << "</select>\n" assert_dom_equal expected, select_date( - Time.mktime(Date.today.year, 8, 16), :prefix => "date[first]" + Time.mktime(Date.today.year, 8, 16), prefix: "date[first]" ) end def test_select_date_with_zero_value - expected = %(<select id="date_first_year" name="date[first][year]">\n) + expected = %(<select id="date_first_year" name="date[first][year]">\n).dup expected << %(<option value="2003">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" @@ -958,12 +985,12 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_date(0, :start_year => 2003, :end_year => 2005, :prefix => "date[first]") + assert_dom_equal expected, select_date(0, start_year: 2003, end_year: 2005, prefix: "date[first]") end def test_select_date_with_zero_value_and_no_start_year - expected = %(<select id="date_first_year" name="date[first][year]">\n) - (Date.today.year-5).upto(Date.today.year+1) { |y| expected << %(<option value="#{y}">#{y}</option>\n) } + expected = %(<select id="date_first_year" name="date[first][year]">\n).dup + (Date.today.year - 5).upto(Date.today.year + 1) { |y| expected << %(<option value="#{y}">#{y}</option>\n) } expected << "</select>\n" expected << %(<select id="date_first_month" name="date[first][month]">\n) @@ -974,11 +1001,11 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_date(0, :end_year => Date.today.year+1, :prefix => "date[first]") + assert_dom_equal expected, select_date(0, end_year: Date.today.year + 1, prefix: "date[first]") end def test_select_date_with_zero_value_and_no_end_year - expected = %(<select id="date_first_year" name="date[first][year]">\n) + expected = %(<select id="date_first_year" name="date[first][year]">\n).dup last_year = Time.now.year + 5 2003.upto(last_year) { |y| expected << %(<option value="#{y}">#{y}</option>\n) } expected << "</select>\n" @@ -991,12 +1018,12 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_date(0, :start_year => 2003, :prefix => "date[first]") + assert_dom_equal expected, select_date(0, start_year: 2003, prefix: "date[first]") end def test_select_date_with_zero_value_and_no_start_and_end_year - expected = %(<select id="date_first_year" name="date[first][year]">\n) - (Date.today.year-5).upto(Date.today.year+5) { |y| expected << %(<option value="#{y}">#{y}</option>\n) } + expected = %(<select id="date_first_year" name="date[first][year]">\n).dup + (Date.today.year - 5).upto(Date.today.year + 5) { |y| expected << %(<option value="#{y}">#{y}</option>\n) } expected << "</select>\n" expected << %(<select id="date_first_month" name="date[first][month]">\n) @@ -1007,12 +1034,12 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_date(0, :prefix => "date[first]") + assert_dom_equal expected, select_date(0, prefix: "date[first]") end def test_select_date_with_nil_value_and_no_start_and_end_year - expected = %(<select id="date_first_year" name="date[first][year]">\n) - (Date.today.year-5).upto(Date.today.year+5) { |y| expected << %(<option value="#{y}">#{y}</option>\n) } + expected = %(<select id="date_first_year" name="date[first][year]">\n).dup + (Date.today.year - 5).upto(Date.today.year + 5) { |y| expected << %(<option value="#{y}">#{y}</option>\n) } expected << "</select>\n" expected << %(<select id="date_first_month" name="date[first][month]">\n) @@ -1023,11 +1050,11 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_date(nil, :prefix => "date[first]") + assert_dom_equal expected, select_date(nil, prefix: "date[first]") end def test_select_date_with_html_options - expected = %(<select id="date_first_year" name="date[first][year]" class="selector">\n) + expected = %(<select id="date_first_year" name="date[first][year]" class="selector">\n).dup expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" @@ -1039,11 +1066,11 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), {:start_year => 2003, :end_year => 2005, :prefix => "date[first]"}, :class => "selector") + assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { start_year: 2003, end_year: 2005, prefix: "date[first]" }, { class: "selector" }) end def test_select_date_with_separator - expected = %(<select id="date_first_year" name="date[first][year]">\n) + expected = %(<select id="date_first_year" name="date[first][year]">\n).dup expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" @@ -1059,11 +1086,11 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { :date_separator => " / ", :start_year => 2003, :end_year => 2005, :prefix => "date[first]"}) + assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), date_separator: " / ", start_year: 2003, end_year: 2005, prefix: "date[first]") end def test_select_date_with_separator_and_discard_day - expected = %(<select id="date_first_year" name="date[first][year]">\n) + expected = %(<select id="date_first_year" name="date[first][year]">\n).dup expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" @@ -1075,31 +1102,31 @@ class DateHelperTest < ActionView::TestCase expected << %(<input type="hidden" id="date_first_day" name="date[first][day]" value="1" />\n) - assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { :date_separator => " / ", :discard_day => true, :start_year => 2003, :end_year => 2005, :prefix => "date[first]"}) + assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), date_separator: " / ", discard_day: true, start_year: 2003, end_year: 2005, prefix: "date[first]") end def test_select_date_with_separator_discard_month_and_day - expected = %(<select id="date_first_year" name="date[first][year]">\n) + expected = %(<select id="date_first_year" name="date[first][year]">\n).dup expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" expected << %(<input type="hidden" id="date_first_month" name="date[first][month]" value="8" />\n) expected << %(<input type="hidden" id="date_first_day" name="date[first][day]" value="1" />\n) - assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { :date_separator => " / ", :discard_month => true, :discard_day => true, :start_year => 2003, :end_year => 2005, :prefix => "date[first]"}) + assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), date_separator: " / ", discard_month: true, discard_day: true, start_year: 2003, end_year: 2005, prefix: "date[first]") end def test_select_date_with_hidden - expected = %(<input id="date_first_year" name="date[first][year]" type="hidden" value="2003"/>\n) + expected = %(<input id="date_first_year" name="date[first][year]" type="hidden" value="2003"/>\n).dup expected << %(<input id="date_first_month" name="date[first][month]" type="hidden" value="8" />\n) expected << %(<input id="date_first_day" name="date[first][day]" type="hidden" value="16" />\n) - assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { :prefix => "date[first]", :use_hidden => true }) - assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { :date_separator => " / ", :prefix => "date[first]", :use_hidden => true }) + assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), prefix: "date[first]", use_hidden: true) + assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), date_separator: " / ", prefix: "date[first]", use_hidden: true) end def test_select_date_with_css_classes_option - expected = %(<select id="date_first_year" name="date[first][year]" class="year">\n) + expected = %(<select id="date_first_year" name="date[first][year]" class="year">\n).dup expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" @@ -1111,11 +1138,11 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), {:start_year => 2003, :end_year => 2005, :prefix => "date[first]", :with_css_classes => true}) + assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), start_year: 2003, end_year: 2005, prefix: "date[first]", with_css_classes: true) end def test_select_date_with_custom_with_css_classes - expected = %(<select id="date_year" name="date[year]" class="my-year">\n) + expected = %(<select id="date_year" name="date[year]" class="my-year">\n).dup expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" @@ -1127,11 +1154,11 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), start_year: 2003, end_year: 2005, with_css_classes: { year: 'my-year', month: 'my-month', day: 'my-day' }) + assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), start_year: 2003, end_year: 2005, with_css_classes: { year: "my-year", month: "my-month", day: "my-day" }) end def test_select_date_with_css_classes_option_and_html_class_option - expected = %(<select id="date_first_year" name="date[first][year]" class="datetime optional year">\n) + expected = %(<select id="date_first_year" name="date[first][year]" class="datetime optional year">\n).dup expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" @@ -1143,11 +1170,11 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), {:start_year => 2003, :end_year => 2005, :prefix => "date[first]", :with_css_classes => true}, { class: 'datetime optional' }) + assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { start_year: 2003, end_year: 2005, prefix: "date[first]", with_css_classes: true }, { class: "datetime optional" }) end def test_select_date_with_custom_with_css_classes_and_html_class_option - expected = %(<select id="date_year" name="date[year]" class="date optional my-year">\n) + expected = %(<select id="date_year" name="date[year]" class="date optional my-year">\n).dup expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" @@ -1159,11 +1186,11 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), {start_year: 2003, end_year: 2005, with_css_classes: { year: 'my-year', month: 'my-month', day: 'my-day' }}, { class: 'date optional' }) + assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { start_year: 2003, end_year: 2005, with_css_classes: { year: "my-year", month: "my-month", day: "my-day" } }, { class: "date optional" }) end def test_select_date_with_partial_with_css_classes_and_html_class_option - expected = %(<select id="date_year" name="date[year]" class="date optional">\n) + expected = %(<select id="date_year" name="date[year]" class="date optional">\n).dup expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" @@ -1175,11 +1202,11 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), {start_year: 2003, end_year: 2005, with_css_classes: { month: 'my-month custom-grid' }}, { class: 'date optional' }) + assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { start_year: 2003, end_year: 2005, with_css_classes: { month: "my-month custom-grid" } }, { class: "date optional" }) end def test_select_date_with_html_class_option - expected = %(<select id="date_year" name="date[year]" class="date optional custom-grid">\n) + expected = %(<select id="date_year" name="date[year]" class="date optional custom-grid">\n).dup expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" @@ -1191,11 +1218,11 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { start_year: 2003, end_year: 2005 }, { class: 'date optional custom-grid' }) + assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { start_year: 2003, end_year: 2005 }, { class: "date optional custom-grid" }) end def test_select_datetime - expected = %(<select id="date_first_year" name="date[first][year]">\n) + expected = %(<select id="date_first_year" name="date[first][year]">\n).dup expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" @@ -1219,11 +1246,11 @@ class DateHelperTest < ActionView::TestCase expected << %(<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" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<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_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), :start_year => 2003, :end_year => 2005, :prefix => "date[first]") + assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), start_year: 2003, end_year: 2005, prefix: "date[first]") end def test_select_datetime_with_ampm - expected = %(<select id="date_first_year" name="date[first][year]">\n) + expected = %(<select id="date_first_year" name="date[first][year]">\n).dup expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" @@ -1247,11 +1274,11 @@ class DateHelperTest < ActionView::TestCase expected << %(<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" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<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_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), :start_year => 2003, :end_year => 2005, :prefix => "date[first]", :ampm => true) + assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), start_year: 2003, end_year: 2005, prefix: "date[first]", ampm: true) end def test_select_datetime_with_separators - expected = %(<select id="date_first_year" name="date[first][year]">\n) + expected = %(<select id="date_first_year" name="date[first][year]">\n).dup expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" @@ -1275,12 +1302,12 @@ class DateHelperTest < ActionView::TestCase expected << %(<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" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<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_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), :start_year => 2003, :end_year => 2005, :prefix => "date[first]", :datetime_separator => ' — ', :time_separator => ' : ') + assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), start_year: 2003, end_year: 2005, prefix: "date[first]", datetime_separator: " — ", time_separator: " : ") end def test_select_datetime_with_nil_value_and_no_start_and_end_year - expected = %(<select id="date_first_year" name="date[first][year]">\n) - (Date.today.year-5).upto(Date.today.year+5) { |y| expected << %(<option value="#{y}">#{y}</option>\n) } + expected = %(<select id="date_first_year" name="date[first][year]">\n).dup + (Date.today.year - 5).upto(Date.today.year + 5) { |y| expected << %(<option value="#{y}">#{y}</option>\n) } expected << "</select>\n" expected << %(<select id="date_first_month" name="date[first][month]">\n) @@ -1303,15 +1330,14 @@ class DateHelperTest < ActionView::TestCase expected << %(<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">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_datetime(nil, :prefix => "date[first]") + assert_dom_equal expected, select_datetime(nil, prefix: "date[first]") end def test_select_datetime_with_html_options - expected = %(<select id="date_first_year" name="date[first][year]" class="selector">\n) + expected = %(<select id="date_first_year" name="date[first][year]" class="selector">\n).dup expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" - expected << %(<select id="date_first_month" name="date[first][month]" class="selector">\n) expected << %(<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n) expected << "</select>\n" @@ -1332,11 +1358,11 @@ class DateHelperTest < ActionView::TestCase expected << %(<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" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<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_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), {:start_year => 2003, :end_year => 2005, :prefix => "date[first]"}, :class => 'selector') + assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), { start_year: 2003, end_year: 2005, prefix: "date[first]" }, { class: "selector" }) end def test_select_datetime_with_all_separators - expected = %(<select id="date_first_year" name="date[first][year]" class="selector">\n) + expected = %(<select id="date_first_year" name="date[first][year]" class="selector">\n).dup expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" @@ -1364,7 +1390,7 @@ class DateHelperTest < ActionView::TestCase expected << %(<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" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<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_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), { :datetime_separator => "—", :date_separator => "/", :time_separator => ":", :start_year => 2003, :end_year => 2005, :prefix => "date[first]"}, :class => 'selector') + assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), { datetime_separator: "—", date_separator: "/", time_separator: ":", start_year: 2003, end_year: 2005, prefix: "date[first]" }, { class: "selector" }) end def test_select_datetime_should_work_with_date @@ -1372,7 +1398,7 @@ class DateHelperTest < ActionView::TestCase end def test_select_datetime_with_default_prompt - expected = %(<select id="date_first_year" name="date[first][year]">\n) + expected = %(<select id="date_first_year" name="date[first][year]">\n).dup expected << %(<option value="">Year</option>\n<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" @@ -1396,13 +1422,12 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="">Minute</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" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<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_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), :start_year => 2003, :end_year => 2005, - :prefix => "date[first]", :prompt => true) + assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), start_year: 2003, end_year: 2005, + prefix: "date[first]", prompt: true) end def test_select_datetime_with_custom_prompt - - expected = %(<select id="date_first_year" name="date[first][year]">\n) + expected = %(<select id="date_first_year" name="date[first][year]">\n).dup expected << %(<option value="">Choose year</option>\n<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" @@ -1426,12 +1451,12 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="">Choose minute</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" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<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_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), :start_year => 2003, :end_year => 2005, :prefix => "date[first]", - :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year', :hour => 'Choose hour', :minute => 'Choose minute'}) + assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), start_year: 2003, end_year: 2005, prefix: "date[first]", + prompt: { day: "Choose day", month: "Choose month", year: "Choose year", hour: "Choose hour", minute: "Choose minute" }) end def test_select_datetime_with_generic_with_css_classes - expected = %(<select id="date_year" name="date[year]" class="year">\n) + expected = %(<select id="date_year" name="date[year]" class="year">\n).dup expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" @@ -1459,7 +1484,7 @@ class DateHelperTest < ActionView::TestCase end def test_select_datetime_with_custom_with_css_classes - expected = %(<select id="date_year" name="date[year]" class="my-year">\n) + expected = %(<select id="date_year" name="date[year]" class="my-year">\n).dup expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" @@ -1483,11 +1508,11 @@ class DateHelperTest < ActionView::TestCase expected << %(<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" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<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_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), start_year: 2003, end_year: 2005, with_css_classes: { day: 'my-day', month: 'my-month', year: 'my-year', hour: 'my-hour', minute: 'my-minute' }) + assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), start_year: 2003, end_year: 2005, with_css_classes: { day: "my-day", month: "my-month", year: "my-year", hour: "my-hour", minute: "my-minute" }) end def test_select_datetime_with_custom_hours - expected = %(<select id="date_first_year" name="date[first][year]">\n) + expected = %(<select id="date_first_year" name="date[first][year]">\n).dup expected << %(<option value="">Choose year</option>\n<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n) expected << "</select>\n" @@ -1511,24 +1536,24 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="">Choose minute</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" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<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_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), :start_year => 2003, :end_year => 2005, :start_hour => 1, :end_hour => 9, :prefix => "date[first]", - :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year', :hour => 'Choose hour', :minute => 'Choose minute'}) + assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), start_year: 2003, end_year: 2005, start_hour: 1, end_hour: 9, prefix: "date[first]", + prompt: { day: "Choose day", month: "Choose month", year: "Choose year", hour: "Choose hour", minute: "Choose minute" }) end def test_select_datetime_with_hidden - expected = %(<input id="date_first_year" name="date[first][year]" type="hidden" value="2003" />\n) + expected = %(<input id="date_first_year" name="date[first][year]" type="hidden" value="2003" />\n).dup expected << %(<input id="date_first_month" name="date[first][month]" type="hidden" value="8" />\n) expected << %(<input id="date_first_day" name="date[first][day]" type="hidden" value="16" />\n) expected << %(<input id="date_first_hour" name="date[first][hour]" type="hidden" value="8" />\n) expected << %(<input id="date_first_minute" name="date[first][minute]" type="hidden" value="4" />\n) - assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), :prefix => "date[first]", :use_hidden => true) - assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), :datetime_separator => "—", :date_separator => "/", - :time_separator => ":", :prefix => "date[first]", :use_hidden => true) + assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), prefix: "date[first]", use_hidden: true) + assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), datetime_separator: "—", date_separator: "/", + time_separator: ":", prefix: "date[first]", use_hidden: true) end def test_select_time - expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n) + expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n).dup expected << %(<input name="date[month]" id="date_month" value="8" type="hidden" />\n) expected << %(<input name="date[day]" id="date_day" value="16" type="hidden" />\n) @@ -1543,11 +1568,11 @@ class DateHelperTest < ActionView::TestCase expected << "</select>\n" assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18)) - assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), :include_seconds => false) + assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), include_seconds: false) end def test_select_time_with_ampm - expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n) + expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n).dup expected << %(<input name="date[month]" id="date_month" value="8" type="hidden" />\n) expected << %(<input name="date[day]" id="date_day" value="16" type="hidden" />\n) @@ -1561,11 +1586,11 @@ class DateHelperTest < ActionView::TestCase expected << %(<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" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<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), :include_seconds => false, :ampm => true) + assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), include_seconds: false, ampm: true) end def test_select_time_with_separator - expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n) + expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n).dup expected << %(<input name="date[month]" id="date_month" value="8" type="hidden" />\n) expected << %(<input name="date[day]" id="date_day" value="16" type="hidden" />\n) expected << %(<select id="date_hour" name="date[hour]">\n) @@ -1578,12 +1603,12 @@ class DateHelperTest < ActionView::TestCase expected << %(<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" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<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), :time_separator => ' : ') - assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), :time_separator => ' : ', :include_seconds => false) + assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), time_separator: " : ") + assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), time_separator: " : ", include_seconds: false) end def test_select_time_with_seconds - expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n) + expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n).dup expected << %(<input name="date[month]" id="date_month" value="8" type="hidden" />\n) expected << %(<input name="date[day]" id="date_day" value="16" type="hidden" />\n) @@ -1591,23 +1616,23 @@ class DateHelperTest < ActionView::TestCase expected << %(<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" selected="selected">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n) expected << "</select>\n" - expected << ' : ' + expected << " : " expected << %(<select id="date_minute" name="date[minute]">\n) expected << %(<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" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<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" - expected << ' : ' + expected << " : " expected << %(<select id="date_second" name="date[second]">\n) expected << %(<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), :include_seconds => true) + assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), include_seconds: true) end def test_select_time_with_seconds_and_separator - expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n) + expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n).dup expected << %(<input name="date[month]" id="date_month" value="8" type="hidden" />\n) expected << %(<input name="date[day]" id="date_day" value="16" type="hidden" />\n) @@ -1627,11 +1652,11 @@ class DateHelperTest < ActionView::TestCase expected << %(<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), :include_seconds => true, :time_separator => ' : ') + assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), include_seconds: true, time_separator: " : ") end def test_select_time_with_html_options - expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n) + expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n).dup expected << %(<input name="date[month]" id="date_month" value="8" type="hidden" />\n) expected << %(<input name="date[day]" id="date_day" value="16" type="hidden" />\n) @@ -1645,8 +1670,8 @@ class DateHelperTest < ActionView::TestCase expected << %(<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" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<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), {}, :class => 'selector') - assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), {:include_seconds => false}, :class => 'selector') + assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), {}, { class: "selector" }) + assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), { include_seconds: false }, { class: "selector" }) end def test_select_time_should_work_with_date @@ -1654,7 +1679,7 @@ class DateHelperTest < ActionView::TestCase end def test_select_time_with_default_prompt - expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n) + expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n).dup expected << %(<input name="date[month]" id="date_month" value="8" type="hidden" />\n) expected << %(<input name="date[day]" id="date_day" value="16" type="hidden" />\n) @@ -1674,11 +1699,11 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="">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), :include_seconds => true, :prompt => true) + assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), include_seconds: true, prompt: true) end def test_select_time_with_custom_prompt - expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n) + expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n).dup expected << %(<input name="date[month]" id="date_month" value="8" type="hidden" />\n) expected << %(<input name="date[day]" id="date_day" value="16" type="hidden" />\n) @@ -1698,12 +1723,12 @@ 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), :include_seconds => true, - :prompt => {:hour => 'Choose hour', :minute => 'Choose minute', :second => 'Choose seconds'}) + 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 def test_select_time_with_generic_with_css_classes - expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n) + expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n).dup expected << %(<input name="date[month]" id="date_month" value="8" type="hidden" />\n) expected << %(<input name="date[day]" id="date_day" value="16" type="hidden" />\n) @@ -1727,7 +1752,7 @@ class DateHelperTest < ActionView::TestCase end def test_select_time_with_custom_with_css_classes - expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n) + expected = %(<input name="date[year]" id="date_year" value="2003" type="hidden" />\n).dup expected << %(<input name="date[month]" id="date_month" value="8" type="hidden" />\n) expected << %(<input name="date[day]" id="date_day" value="16" type="hidden" />\n) @@ -1747,25 +1772,25 @@ class DateHelperTest < ActionView::TestCase expected << %(<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), include_seconds: true, with_css_classes: { hour: 'my-hour', minute: 'my-minute', second: 'my-second' }) + assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), include_seconds: true, with_css_classes: { hour: "my-hour", minute: "my-minute", second: "my-second" }) end def test_select_time_with_hidden - expected = %(<input id="date_first_year" name="date[first][year]" type="hidden" value="2003" />\n) + expected = %(<input id="date_first_year" name="date[first][year]" type="hidden" value="2003" />\n).dup expected << %(<input id="date_first_month" name="date[first][month]" type="hidden" value="8" />\n) expected << %(<input id="date_first_day" name="date[first][day]" type="hidden" value="16" />\n) expected << %(<input id="date_first_hour" name="date[first][hour]" type="hidden" value="8" />\n) expected << %(<input id="date_first_minute" name="date[first][minute]" type="hidden" value="4" />\n) - assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), :prefix => "date[first]", :use_hidden => true) - assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), :time_separator => ":", :prefix => "date[first]", :use_hidden => true) + assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), prefix: "date[first]", use_hidden: true) + assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), time_separator: ":", prefix: "date[first]", use_hidden: true) end def test_date_select @post = Post.new @post.written_on = Date.new(2004, 6, 15) - expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n} + expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}.dup expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -1785,7 +1810,7 @@ class DateHelperTest < ActionView::TestCase @post = Post.new @post.written_on = Date.new(2004, 6, 15) - expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n} + expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}.dup expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option selected="selected" value="2004">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -1798,14 +1823,14 @@ class DateHelperTest < ActionView::TestCase expected << "</select>\n" - assert_dom_equal expected, date_select("post", "written_on", :selected => Date.new(2004, 07, 10)) + assert_dom_equal expected, date_select("post", "written_on", selected: Date.new(2004, 07, 10)) end def test_date_select_with_selected_in_hash @post = Post.new @post.written_on = Date.new(2004, 6, 15) - expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n} + expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}.dup expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option selected="selected" value="2004">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -1818,7 +1843,7 @@ class DateHelperTest < ActionView::TestCase expected << "</select>\n" - assert_dom_equal expected, date_select("post", "written_on", :selected => {day: 10, month: 07, year: 2004}) + assert_dom_equal expected, date_select("post", "written_on", selected: { day: 10, month: 07, year: 2004 }) end def test_date_select_with_selected_nil @@ -1843,9 +1868,9 @@ class DateHelperTest < ActionView::TestCase @post = Post.new @post.written_on = Date.new(2004, 6, 15) - expected = "<input type=\"hidden\" id=\"post_written_on_3i\" name=\"post[written_on(3i)]\" value=\"1\" />\n" + expected = "<input type=\"hidden\" id=\"post_written_on_3i\" name=\"post[written_on(3i)]\" value=\"1\" />\n".dup - expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n} + expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n} expected << %{<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n} expected << "</select>\n" @@ -1853,30 +1878,30 @@ class DateHelperTest < ActionView::TestCase expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" - assert_dom_equal expected, date_select("post", "written_on", :order => [ :month, :year ]) + assert_dom_equal expected, date_select("post", "written_on", order: [ :month, :year ]) end def test_date_select_without_day_and_month @post = Post.new @post.written_on = Date.new(2004, 2, 29) - expected = "<input type=\"hidden\" id=\"post_written_on_2i\" name=\"post[written_on(2i)]\" value=\"2\" />\n" + expected = "<input type=\"hidden\" id=\"post_written_on_2i\" name=\"post[written_on(2i)]\" value=\"2\" />\n".dup expected << "<input type=\"hidden\" id=\"post_written_on_3i\" name=\"post[written_on(3i)]\" value=\"1\" />\n" expected << %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n} expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" - assert_dom_equal expected, date_select("post", "written_on", :order => [ :year ]) + assert_dom_equal expected, date_select("post", "written_on", order: [ :year ]) end def test_date_select_without_day_with_separator @post = Post.new @post.written_on = Date.new(2004, 6, 15) - expected = "<input type=\"hidden\" id=\"post_written_on_3i\" name=\"post[written_on(3i)]\" value=\"1\" />\n" + expected = "<input type=\"hidden\" id=\"post_written_on_3i\" name=\"post[written_on(3i)]\" value=\"1\" />\n".dup - expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n} + expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n} expected << %{<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n} expected << "</select>\n" @@ -1886,16 +1911,16 @@ class DateHelperTest < ActionView::TestCase expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" - assert_dom_equal expected, date_select("post", "written_on", :date_separator => '/', :order => [ :month, :year ]) + assert_dom_equal expected, date_select("post", "written_on", date_separator: "/", order: [ :month, :year ]) end def test_date_select_without_day_and_with_disabled_html_option @post = Post.new @post.written_on = Date.new(2004, 6, 15) - expected = "<input type=\"hidden\" id=\"post_written_on_3i\" disabled=\"disabled\" name=\"post[written_on(3i)]\" value=\"1\" />\n" + expected = "<input type=\"hidden\" id=\"post_written_on_3i\" disabled=\"disabled\" name=\"post[written_on(3i)]\" value=\"1\" />\n".dup - expected << %{<select id="post_written_on_2i" disabled="disabled" name="post[written_on(2i)]">\n} + expected << %{<select id="post_written_on_2i" disabled="disabled" name="post[written_on(2i)]">\n} expected << %{<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6" selected="selected">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n} expected << "</select>\n" @@ -1903,7 +1928,7 @@ class DateHelperTest < ActionView::TestCase expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" - assert_dom_equal expected, date_select("post", "written_on", { :order => [ :month, :year ] }, :disabled => true) + assert_dom_equal expected, date_select("post", "written_on", { order: [ :month, :year ] }, { disabled: true }) end def test_date_select_within_fields_for @@ -1914,7 +1939,7 @@ class DateHelperTest < ActionView::TestCase concat f.date_select(:written_on) end - expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option selected="selected" value="2004">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n</select>\n} + expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option selected="selected" value="2004">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n</select>\n}.dup expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option selected="selected" value="6">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n</select>\n} expected << %{<select id="post_written_on_3i" name="post[written_on(3i)]">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option selected="selected" value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n</select>\n} @@ -1926,11 +1951,11 @@ class DateHelperTest < ActionView::TestCase @post.written_on = Date.new(2004, 6, 15) id = 27 - output_buffer = fields_for :post, @post, :index => id do |f| + output_buffer = fields_for :post, @post, index: id do |f| concat f.date_select(:written_on) end - expected = %{<select id="post_#{id}_written_on_1i" name="post[#{id}][written_on(1i)]">\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option selected="selected" value="2004">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n</select>\n} + expected = %{<select id="post_#{id}_written_on_1i" name="post[#{id}][written_on(1i)]">\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option selected="selected" value="2004">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n</select>\n}.dup expected << %{<select id="post_#{id}_written_on_2i" name="post[#{id}][written_on(2i)]">\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option selected="selected" value="6">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n</select>\n} expected << %{<select id="post_#{id}_written_on_3i" name="post[#{id}][written_on(3i)]">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option selected="selected" value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n</select>\n} @@ -1942,12 +1967,11 @@ class DateHelperTest < ActionView::TestCase @post.written_on = Date.new(2004, 6, 15) id = nil - output_buffer = fields_for :post, @post, :index => id do |f| + output_buffer = fields_for :post, @post, index: id do |f| concat f.date_select(:written_on) end - - expected = %{<select id="post_#{id}_written_on_1i" name="post[#{id}][written_on(1i)]">\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option selected="selected" value="2004">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n</select>\n} + expected = %{<select id="post_#{id}_written_on_1i" name="post[#{id}][written_on(1i)]">\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option selected="selected" value="2004">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n</select>\n}.dup expected << %{<select id="post_#{id}_written_on_2i" name="post[#{id}][written_on(2i)]">\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option selected="selected" value="6">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n</select>\n} expected << %{<select id="post_#{id}_written_on_3i" name="post[#{id}][written_on(3i)]">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option selected="selected" value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n</select>\n} @@ -1959,7 +1983,7 @@ class DateHelperTest < ActionView::TestCase @post.written_on = Date.new(2004, 6, 15) id = 456 - expected = %{<select id="post_456_written_on_1i" name="post[#{id}][written_on(1i)]">\n} + expected = %{<select id="post_456_written_on_1i" name="post[#{id}][written_on(1i)]">\n}.dup expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -1971,7 +1995,7 @@ class DateHelperTest < ActionView::TestCase expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n} expected << "</select>\n" - assert_dom_equal expected, date_select("post", "written_on", :index => id) + assert_dom_equal expected, date_select("post", "written_on", index: id) end def test_date_select_with_auto_index @@ -1979,7 +2003,7 @@ class DateHelperTest < ActionView::TestCase @post.written_on = Date.new(2004, 6, 15) id = 123 - expected = %{<select id="post_123_written_on_1i" name="post[#{id}][written_on(1i)]">\n} + expected = %{<select id="post_123_written_on_1i" name="post[#{id}][written_on(1i)]">\n}.dup expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -1998,7 +2022,7 @@ class DateHelperTest < ActionView::TestCase @post = Post.new @post.written_on = Date.new(2004, 6, 15) - expected = %{<select id="post_written_on_3i" name="post[written_on(3i)]">\n} + expected = %{<select id="post_written_on_3i" name="post[written_on(3i)]">\n}.dup 1.upto(31) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 15}>#{i}</option>\n) } expected << "</select>\n" @@ -2006,19 +2030,19 @@ class DateHelperTest < ActionView::TestCase 1.upto(12) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 6}>#{Date::MONTHNAMES[i]}</option>\n) } expected << "</select>\n" - expected << %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n} + expected << %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n} 1999.upto(2009) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 2004}>#{i}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, date_select("post", "written_on", :order => [:day, :month, :year]) + assert_dom_equal expected, date_select("post", "written_on", order: [:day, :month, :year]) end def test_date_select_with_nil @post = Post.new - start_year = Time.now.year-5 - end_year = Time.now.year+5 - expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n} + start_year = Time.now.year - 5 + end_year = Time.now.year + 5 + expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}.dup start_year.upto(end_year) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == Time.now.year}>#{i}</option>\n) } expected << "</select>\n" @@ -2036,9 +2060,9 @@ class DateHelperTest < ActionView::TestCase def test_date_select_with_nil_and_blank @post = Post.new - start_year = Time.now.year-5 - end_year = Time.now.year+5 - expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n} + start_year = Time.now.year - 5 + end_year = Time.now.year + 5 + expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}.dup expected << "<option value=\"\"></option>\n" start_year.upto(end_year) { |i| expected << %(<option value="#{i}">#{i}</option>\n) } expected << "</select>\n" @@ -2053,17 +2077,17 @@ class DateHelperTest < ActionView::TestCase 1.upto(31) { |i| expected << %(<option value="#{i}">#{i}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, date_select("post", "written_on", :include_blank => true) + assert_dom_equal expected, date_select("post", "written_on", include_blank: true) end def test_date_select_with_nil_and_blank_and_order @post = Post.new - start_year = Time.now.year-5 - end_year = Time.now.year+5 + start_year = Time.now.year - 5 + end_year = Time.now.year + 5 expected = '<input name="post[written_on(3i)]" type="hidden" id="post_written_on_3i" value="1"/>' + "\n" - expected << %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n} + expected << %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n} expected << "<option value=\"\"></option>\n" start_year.upto(end_year) { |i| expected << %(<option value="#{i}">#{i}</option>\n) } expected << "</select>\n" @@ -2073,23 +2097,23 @@ class DateHelperTest < ActionView::TestCase 1.upto(12) { |i| expected << %(<option value="#{i}">#{Date::MONTHNAMES[i]}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, date_select("post", "written_on", :order=>[:year, :month], :include_blank=>true) + assert_dom_equal expected, date_select("post", "written_on", order: [:year, :month], include_blank: true) end def test_date_select_with_nil_and_blank_and_discard_month @post = Post.new - start_year = Time.now.year-5 - end_year = Time.now.year+5 + start_year = Time.now.year - 5 + end_year = Time.now.year + 5 - expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n} + expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}.dup expected << "<option value=\"\"></option>\n" start_year.upto(end_year) { |i| expected << %(<option value="#{i}">#{i}</option>\n) } expected << "</select>\n" expected << '<input name="post[written_on(2i)]" type="hidden" id="post_written_on_2i" value="1"/>' + "\n" expected << '<input name="post[written_on(3i)]" type="hidden" id="post_written_on_3i" value="1"/>' + "\n" - assert_dom_equal expected, date_select("post", "written_on", :discard_month => true, :include_blank=>true) + assert_dom_equal expected, date_select("post", "written_on", discard_month: true, include_blank: true) end def test_date_select_with_nil_and_blank_and_discard_year @@ -2107,14 +2131,14 @@ class DateHelperTest < ActionView::TestCase 1.upto(31) { |i| expected << %(<option value="#{i}">#{i}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, date_select("post", "written_on", :discard_year => true, :include_blank=>true) + assert_dom_equal expected, date_select("post", "written_on", discard_year: true, include_blank: true) end def test_date_select_cant_override_discard_hour @post = Post.new @post.written_on = Date.new(2004, 6, 15) - expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n} + expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}.dup expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -2126,14 +2150,14 @@ class DateHelperTest < ActionView::TestCase expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n} expected << "</select>\n" - assert_dom_equal expected, date_select("post", "written_on", :discard_hour => false) + assert_dom_equal expected, date_select("post", "written_on", discard_hour: false) end def test_date_select_with_html_options @post = Post.new @post.written_on = Date.new(2004, 6, 15) - expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]" class="selector">\n} + expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]" class="selector">\n}.dup expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -2146,7 +2170,7 @@ class DateHelperTest < ActionView::TestCase expected << "</select>\n" - assert_dom_equal expected, date_select("post", "written_on", {}, :class => 'selector') + assert_dom_equal expected, date_select("post", "written_on", {}, { class: "selector" }) end def test_date_select_with_html_options_within_fields_for @@ -2154,10 +2178,10 @@ class DateHelperTest < ActionView::TestCase @post.written_on = Date.new(2004, 6, 15) output_buffer = fields_for :post, @post do |f| - concat f.date_select(:written_on, {}, :class => 'selector') + concat f.date_select(:written_on, {}, { class: "selector" }) end - expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]" class="selector">\n} + expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]" class="selector">\n}.dup expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -2177,7 +2201,7 @@ class DateHelperTest < ActionView::TestCase @post = Post.new @post.written_on = Date.new(2004, 6, 15) - expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n} + expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}.dup expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -2194,14 +2218,14 @@ class DateHelperTest < ActionView::TestCase expected << "</select>\n" - assert_dom_equal expected, date_select("post", "written_on", { :date_separator => " / " }) + assert_dom_equal expected, date_select("post", "written_on", date_separator: " / ") end def test_date_select_with_separator_and_order @post = Post.new @post.written_on = Date.new(2004, 6, 15) - expected = %{<select id="post_written_on_3i" name="post[written_on(3i)]">\n} + expected = %{<select id="post_written_on_3i" name="post[written_on(3i)]">\n}.dup expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n} expected << "</select>\n" @@ -2217,14 +2241,14 @@ class DateHelperTest < ActionView::TestCase expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" - assert_dom_equal expected, date_select("post", "written_on", { :order => [:day, :month, :year], :date_separator => " / " }) + assert_dom_equal expected, date_select("post", "written_on", order: [:day, :month, :year], date_separator: " / ") end def test_date_select_with_separator_and_order_and_year_discarded @post = Post.new @post.written_on = Date.new(2004, 6, 15) - expected = %{<select id="post_written_on_3i" name="post[written_on(3i)]">\n} + expected = %{<select id="post_written_on_3i" name="post[written_on(3i)]">\n}.dup expected << %{<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15" selected="selected">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n} expected << "</select>\n" @@ -2235,14 +2259,14 @@ class DateHelperTest < ActionView::TestCase expected << "</select>\n" expected << %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n} - assert_dom_equal expected, date_select("post", "written_on", { :order => [:day, :month, :year], :discard_year => true, :date_separator => " / " }) + assert_dom_equal expected, date_select("post", "written_on", order: [:day, :month, :year], discard_year: true, date_separator: " / ") end def test_date_select_with_default_prompt @post = Post.new @post.written_on = Date.new(2004, 6, 15) - expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n} + expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}.dup expected << %{<option value="">Year</option>\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -2255,14 +2279,14 @@ class DateHelperTest < ActionView::TestCase expected << "</select>\n" - assert_dom_equal expected, date_select("post", "written_on", :prompt => true) + assert_dom_equal expected, date_select("post", "written_on", prompt: true) end def test_date_select_with_custom_prompt @post = Post.new @post.written_on = Date.new(2004, 6, 15) - expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n} + expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]">\n}.dup expected << %{<option value="">Choose year</option>\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -2275,14 +2299,14 @@ class DateHelperTest < ActionView::TestCase expected << "</select>\n" - assert_dom_equal expected, date_select("post", "written_on", :prompt => {:year => 'Choose year', :month => 'Choose month', :day => 'Choose day'}) + assert_dom_equal expected, date_select("post", "written_on", prompt: { year: "Choose year", month: "Choose month", day: "Choose day" }) end def test_date_select_with_generic_with_css_classes @post = Post.new @post.written_on = Date.new(2004, 6, 15) - expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]" class="year">\n} + expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]" class="year">\n}.dup expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -2302,7 +2326,7 @@ class DateHelperTest < ActionView::TestCase @post = Post.new @post.written_on = Date.new(2004, 6, 15) - expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]" class="my-year">\n} + expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]" class="my-year">\n}.dup expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -2315,14 +2339,14 @@ class DateHelperTest < ActionView::TestCase expected << "</select>\n" - assert_dom_equal expected, date_select("post", "written_on", with_css_classes: { year: 'my-year', month: 'my-month', day: 'my-day' }) + assert_dom_equal expected, date_select("post", "written_on", with_css_classes: { year: "my-year", month: "my-month", day: "my-day" }) end def test_time_select @post = Post.new @post.written_on = Time.local(2004, 6, 15, 15, 16, 35) - expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n} + expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n}.dup expected << %{<input type="hidden" id="post_written_on_2i" name="post[written_on(2i)]" value="6" />\n} expected << %{<input type="hidden" id="post_written_on_3i" name="post[written_on(3i)]" value="15" />\n} @@ -2341,7 +2365,7 @@ class DateHelperTest < ActionView::TestCase @post = Post.new @post.written_on = Time.local(2004, 6, 15, 15, 16, 35) - expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n} + expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n}.dup expected << %{<input type="hidden" id="post_written_on_2i" name="post[written_on(2i)]" value="6" />\n} expected << %{<input type="hidden" id="post_written_on_3i" name="post[written_on(3i)]" value="15" />\n} @@ -2360,7 +2384,7 @@ class DateHelperTest < ActionView::TestCase @post = Post.new @post.written_on = Time.local(2004, 6, 15, 15, 16, 35) - expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="1" />\n} + expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="1" />\n}.dup expected << %{<input type="hidden" id="post_written_on_2i" name="post[written_on(2i)]" value="1" />\n} expected << %{<input type="hidden" id="post_written_on_3i" name="post[written_on(3i)]" value="1" />\n} @@ -2379,7 +2403,7 @@ class DateHelperTest < ActionView::TestCase @post = Post.new @post.written_on = Time.local(2004, 6, 15, 15, 16, 35) - expected = %(<select id="post_written_on_4i" name="post[written_on(4i)]">\n) + expected = %(<select id="post_written_on_4i" name="post[written_on(4i)]">\n).dup 0.upto(23) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 15}>#{sprintf("%02d", i)}</option>\n) } expected << "</select>\n" expected << " : " @@ -2387,14 +2411,14 @@ class DateHelperTest < ActionView::TestCase 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, time_select("post", "written_on", :ignore_date => true) + assert_dom_equal expected, time_select("post", "written_on", ignore_date: true) end def test_time_select_with_seconds @post = Post.new @post.written_on = Time.local(2004, 6, 15, 15, 16, 35) - expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n} + expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n}.dup expected << %{<input type="hidden" id="post_written_on_2i" name="post[written_on(2i)]" value="6" />\n} expected << %{<input type="hidden" id="post_written_on_3i" name="post[written_on(3i)]" value="15" />\n} @@ -2410,14 +2434,14 @@ class DateHelperTest < ActionView::TestCase 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 35}>#{sprintf("%02d", i)}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, time_select("post", "written_on", :include_seconds => true) + assert_dom_equal expected, time_select("post", "written_on", include_seconds: true) end def test_time_select_with_html_options @post = Post.new @post.written_on = Time.local(2004, 6, 15, 15, 16, 35) - expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n} + expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n}.dup expected << %{<input type="hidden" id="post_written_on_2i" name="post[written_on(2i)]" value="6" />\n} expected << %{<input type="hidden" id="post_written_on_3i" name="post[written_on(3i)]" value="15" />\n} @@ -2429,7 +2453,7 @@ class DateHelperTest < ActionView::TestCase 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, time_select("post", "written_on", {}, :class => 'selector') + assert_dom_equal expected, time_select("post", "written_on", {}, { class: "selector" }) end def test_time_select_with_html_options_within_fields_for @@ -2437,10 +2461,10 @@ class DateHelperTest < ActionView::TestCase @post.written_on = Time.local(2004, 6, 15, 15, 16, 35) output_buffer = fields_for :post, @post do |f| - concat f.time_select(:written_on, {}, :class => 'selector') + concat f.time_select(:written_on, {}, { class: "selector" }) end - expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n} + expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n}.dup expected << %{<input type="hidden" id="post_written_on_2i" name="post[written_on(2i)]" value="6" />\n} expected << %{<input type="hidden" id="post_written_on_3i" name="post[written_on(3i)]" value="15" />\n} @@ -2459,7 +2483,7 @@ class DateHelperTest < ActionView::TestCase @post = Post.new @post.written_on = Time.local(2004, 6, 15, 15, 16, 35) - expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n} + expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n}.dup expected << %{<input type="hidden" id="post_written_on_2i" name="post[written_on(2i)]" value="6" />\n} expected << %{<input type="hidden" id="post_written_on_3i" name="post[written_on(3i)]" value="15" />\n} @@ -2479,14 +2503,14 @@ class DateHelperTest < ActionView::TestCase 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 35}>#{sprintf("%02d", i)}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, time_select("post", "written_on", { :time_separator => " - ", :include_seconds => true }) + assert_dom_equal expected, time_select("post", "written_on", time_separator: " - ", include_seconds: true) end def test_time_select_with_default_prompt @post = Post.new @post.written_on = Time.local(2004, 6, 15, 15, 16, 35) - expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n} + expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n}.dup expected << %{<input type="hidden" id="post_written_on_2i" name="post[written_on(2i)]" value="6" />\n} expected << %{<input type="hidden" id="post_written_on_3i" name="post[written_on(3i)]" value="15" />\n} @@ -2496,18 +2520,18 @@ class DateHelperTest < ActionView::TestCase expected << "</select>\n" expected << " : " expected << %(<select id="post_written_on_5i" name="post[written_on(5i)]">\n) - expected << %(<option value="">Minute</option>\n) + expected << %(<option value="">Minute</option>\n) 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, time_select("post", "written_on", :prompt => true) + assert_dom_equal expected, time_select("post", "written_on", prompt: true) end def test_time_select_with_custom_prompt @post = Post.new @post.written_on = Time.local(2004, 6, 15, 15, 16, 35) - expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n} + expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n}.dup expected << %{<input type="hidden" id="post_written_on_2i" name="post[written_on(2i)]" value="6" />\n} expected << %{<input type="hidden" id="post_written_on_3i" name="post[written_on(3i)]" value="15" />\n} @@ -2517,18 +2541,18 @@ class DateHelperTest < ActionView::TestCase expected << "</select>\n" expected << " : " expected << %(<select id="post_written_on_5i" name="post[written_on(5i)]">\n) - expected << %(<option value="">Choose minute</option>\n) + expected << %(<option value="">Choose minute</option>\n) 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, time_select("post", "written_on", :prompt => {:hour => 'Choose hour', :minute => 'Choose minute'}) + assert_dom_equal expected, time_select("post", "written_on", prompt: { hour: "Choose hour", minute: "Choose minute" }) end def test_time_select_with_generic_with_css_classes @post = Post.new @post.written_on = Time.local(2004, 6, 15, 15, 16, 35) - expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n} + expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n}.dup expected << %{<input type="hidden" id="post_written_on_2i" name="post[written_on(2i)]" value="6" />\n} expected << %{<input type="hidden" id="post_written_on_3i" name="post[written_on(3i)]" value="15" />\n} @@ -2549,7 +2573,7 @@ class DateHelperTest < ActionView::TestCase @post = Post.new @post.written_on = Time.local(2004, 6, 15, 15, 16, 35) - expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n} + expected = %{<input type="hidden" id="post_written_on_1i" name="post[written_on(1i)]" value="2004" />\n}.dup expected << %{<input type="hidden" id="post_written_on_2i" name="post[written_on(2i)]" value="6" />\n} expected << %{<input type="hidden" id="post_written_on_3i" name="post[written_on(3i)]" value="15" />\n} @@ -2563,14 +2587,14 @@ class DateHelperTest < ActionView::TestCase 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, time_select("post", "written_on", with_css_classes: { hour: 'my-hour', minute: 'my-minute' }) + assert_dom_equal expected, time_select("post", "written_on", with_css_classes: { hour: "my-hour", minute: "my-minute" }) end def test_time_select_with_disabled_html_option @post = Post.new @post.written_on = Time.local(2004, 6, 15, 15, 16, 35) - expected = %{<input type="hidden" id="post_written_on_1i" disabled="disabled" name="post[written_on(1i)]" value="2004" />\n} + expected = %{<input type="hidden" id="post_written_on_1i" disabled="disabled" name="post[written_on(1i)]" value="2004" />\n}.dup expected << %{<input type="hidden" id="post_written_on_2i" disabled="disabled" name="post[written_on(2i)]" value="6" />\n} expected << %{<input type="hidden" id="post_written_on_3i" disabled="disabled" name="post[written_on(3i)]" value="15" />\n} @@ -2582,14 +2606,14 @@ class DateHelperTest < ActionView::TestCase 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, time_select("post", "written_on", {}, :disabled => true) + assert_dom_equal expected, time_select("post", "written_on", {}, { disabled: true }) end def test_datetime_select @post = Post.new @post.updated_at = Time.local(2004, 6, 15, 16, 35) - expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n} + expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}.dup expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -2618,7 +2642,7 @@ class DateHelperTest < ActionView::TestCase @post = Post.new @post.updated_at = Time.local(2004, 6, 15, 16, 35) - expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n} + expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}.dup expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -2640,7 +2664,7 @@ class DateHelperTest < ActionView::TestCase expected << %{<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">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" selected="selected">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, datetime_select("post", "updated_at", :selected => Time.local(2004, 3, 10, 12, 30)) + assert_dom_equal expected, datetime_select("post", "updated_at", selected: Time.local(2004, 3, 10, 12, 30)) end def test_datetime_select_with_selected_nil @@ -2674,7 +2698,7 @@ class DateHelperTest < ActionView::TestCase # The love zone is UTC+0 mytz = Class.new(ActiveSupport::TimeZone) { attr_accessor :now - }.create('tenderlove', 0, ActiveSupport::TimeZone.find_tzinfo('UTC')) + }.create("tenderlove", 0, ActiveSupport::TimeZone.find_tzinfo("UTC")) now = Time.mktime(2004, 6, 15, 16, 35, 0) mytz.now = now @@ -2684,7 +2708,7 @@ class DateHelperTest < ActionView::TestCase @post = Post.new - expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n} + expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}.dup expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -2716,10 +2740,10 @@ class DateHelperTest < ActionView::TestCase @post.updated_at = Time.local(2004, 6, 15, 16, 35) output_buffer = fields_for :post, @post do |f| - concat f.datetime_select(:updated_at, {}, :class => 'selector') + concat f.datetime_select(:updated_at, {}, { class: "selector" }) end - expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]" class="selector">\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option selected="selected" value="2004">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n</select>\n} + expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]" class="selector">\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option selected="selected" value="2004">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n</select>\n}.dup expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]" class="selector">\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option selected="selected" value="6">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n</select>\n} expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]" class="selector">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option selected="selected" value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n</select>\n} expected << %{ — <select id="post_updated_at_4i" name="post[updated_at(4i)]" class="selector">\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 selected="selected" value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n</select>\n} @@ -2732,7 +2756,7 @@ class DateHelperTest < ActionView::TestCase @post = Post.new @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35) - expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n} + expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}.dup expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -2766,7 +2790,7 @@ class DateHelperTest < ActionView::TestCase 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 35}>#{sprintf("%02d", i)}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, datetime_select("post", "updated_at", { :date_separator => " / ", :datetime_separator => " , ", :time_separator => " - ", :include_seconds => true }) + assert_dom_equal expected, datetime_select("post", "updated_at", date_separator: " / ", datetime_separator: " , ", time_separator: " - ", include_seconds: true) end def test_datetime_select_with_integer @@ -2777,7 +2801,7 @@ class DateHelperTest < ActionView::TestCase def test_datetime_select_with_infinity # Float @post = Post.new - @post.updated_at = (-1.0/0) + @post.updated_at = (-1.0 / 0) datetime_select("post", "updated_at") end @@ -2785,7 +2809,7 @@ class DateHelperTest < ActionView::TestCase @post = Post.new @post.updated_at = nil - expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n} + expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}.dup expected << %{<option value="">Year</option>\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -2807,14 +2831,14 @@ class DateHelperTest < ActionView::TestCase expected << %{<option value="">Minute</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">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, datetime_select("post", "updated_at", :start_year=>1999, :end_year=>2009, :prompt => true) + assert_dom_equal expected, datetime_select("post", "updated_at", start_year: 1999, end_year: 2009, prompt: true) end def test_datetime_select_with_custom_prompt @post = Post.new @post.updated_at = nil - expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n} + expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}.dup expected << %{<option value="">Choose year</option>\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -2836,14 +2860,14 @@ class DateHelperTest < ActionView::TestCase expected << %{<option value="">Choose minute</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">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, datetime_select("post", "updated_at", :start_year=>1999, :end_year=>2009, :prompt => {:year => 'Choose year', :month => 'Choose month', :day => 'Choose day', :hour => 'Choose hour', :minute => 'Choose minute'}) + assert_dom_equal expected, datetime_select("post", "updated_at", start_year: 1999, end_year: 2009, prompt: { year: "Choose year", month: "Choose month", day: "Choose day", hour: "Choose hour", minute: "Choose minute" }) end def test_datetime_select_with_generic_with_css_classes @post = Post.new @post.written_on = Time.local(2004, 6, 15, 15, 16, 35) - expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]" class="year">\n} + expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]" class="year">\n}.dup expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -2872,7 +2896,7 @@ class DateHelperTest < ActionView::TestCase @post = Post.new @post.written_on = Time.local(2004, 6, 15, 15, 16, 35) - expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]" class="my-year">\n} + expected = %{<select id="post_written_on_1i" name="post[written_on(1i)]" class="my-year">\n}.dup expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -2894,12 +2918,12 @@ class DateHelperTest < ActionView::TestCase expected << %{<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" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n<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, datetime_select("post", "written_on", start_year: 1999, end_year: 2009, with_css_classes: { year: 'my-year', month: 'my-month', day: 'my-day', hour: 'my-hour', minute: 'my-minute' }) + assert_dom_equal expected, datetime_select("post", "written_on", start_year: 1999, end_year: 2009, with_css_classes: { year: "my-year", month: "my-month", day: "my-day", hour: "my-hour", minute: "my-minute" }) end def test_date_select_with_zero_value_and_no_start_year - expected = %(<select id="date_first_year" name="date[first][year]">\n) - (Date.today.year-5).upto(Date.today.year+1) { |y| expected << %(<option value="#{y}">#{y}</option>\n) } + expected = %(<select id="date_first_year" name="date[first][year]">\n).dup + (Date.today.year - 5).upto(Date.today.year + 1) { |y| expected << %(<option value="#{y}">#{y}</option>\n) } expected << "</select>\n" expected << %(<select id="date_first_month" name="date[first][month]">\n) @@ -2910,11 +2934,11 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_date(0, :end_year => Date.today.year+1, :prefix => "date[first]") + assert_dom_equal expected, select_date(0, end_year: Date.today.year + 1, prefix: "date[first]") end def test_date_select_with_zero_value_and_no_end_year - expected = %(<select id="date_first_year" name="date[first][year]">\n) + expected = %(<select id="date_first_year" name="date[first][year]">\n).dup last_year = Time.now.year + 5 2003.upto(last_year) { |y| expected << %(<option value="#{y}">#{y}</option>\n) } expected << "</select>\n" @@ -2927,12 +2951,12 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_date(0, :start_year => 2003, :prefix => "date[first]") + assert_dom_equal expected, select_date(0, start_year: 2003, prefix: "date[first]") end def test_date_select_with_zero_value_and_no_start_and_end_year - expected = %(<select id="date_first_year" name="date[first][year]">\n) - (Date.today.year-5).upto(Date.today.year+5) { |y| expected << %(<option value="#{y}">#{y}</option>\n) } + expected = %(<select id="date_first_year" name="date[first][year]">\n).dup + (Date.today.year - 5).upto(Date.today.year + 5) { |y| expected << %(<option value="#{y}">#{y}</option>\n) } expected << "</select>\n" expected << %(<select id="date_first_month" name="date[first][month]">\n) @@ -2943,12 +2967,12 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_date(0, :prefix => "date[first]") + assert_dom_equal expected, select_date(0, prefix: "date[first]") end def test_date_select_with_nil_value_and_no_start_and_end_year - expected = %(<select id="date_first_year" name="date[first][year]">\n) - (Date.today.year-5).upto(Date.today.year+5) { |y| expected << %(<option value="#{y}">#{y}</option>\n) } + expected = %(<select id="date_first_year" name="date[first][year]">\n).dup + (Date.today.year - 5).upto(Date.today.year + 5) { |y| expected << %(<option value="#{y}">#{y}</option>\n) } expected << "</select>\n" expected << %(<select id="date_first_month" name="date[first][month]">\n) @@ -2959,12 +2983,12 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_date(nil, :prefix => "date[first]") + assert_dom_equal expected, select_date(nil, prefix: "date[first]") end def test_datetime_select_with_nil_value_and_no_start_and_end_year - expected = %(<select id="date_first_year" name="date[first][year]">\n) - (Date.today.year-5).upto(Date.today.year+5) { |y| expected << %(<option value="#{y}">#{y}</option>\n) } + expected = %(<select id="date_first_year" name="date[first][year]">\n).dup + (Date.today.year - 5).upto(Date.today.year + 5) { |y| expected << %(<option value="#{y}">#{y}</option>\n) } expected << "</select>\n" expected << %(<select id="date_first_month" name="date[first][month]">\n) @@ -2987,7 +3011,7 @@ class DateHelperTest < ActionView::TestCase expected << %(<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">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_datetime(nil, :prefix => "date[first]") + assert_dom_equal expected, select_datetime(nil, prefix: "date[first]") end def test_datetime_select_with_options_index @@ -2995,7 +3019,7 @@ class DateHelperTest < ActionView::TestCase @post.updated_at = Time.local(2004, 6, 15, 16, 35) id = 456 - expected = %{<select id="post_456_updated_at_1i" name="post[#{id}][updated_at(1i)]">\n} + expected = %{<select id="post_456_updated_at_1i" name="post[#{id}][updated_at(1i)]">\n}.dup expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -3017,7 +3041,7 @@ class DateHelperTest < ActionView::TestCase expected << %{<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">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" selected="selected">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, datetime_select("post", "updated_at", :index => id) + assert_dom_equal expected, datetime_select("post", "updated_at", index: id) end def test_datetime_select_within_fields_for_with_options_index @@ -3025,11 +3049,11 @@ class DateHelperTest < ActionView::TestCase @post.updated_at = Time.local(2004, 6, 15, 16, 35) id = 456 - output_buffer = fields_for :post, @post, :index => id do |f| + output_buffer = fields_for :post, @post, index: id do |f| concat f.datetime_select(:updated_at) end - expected = %{<select id="post_456_updated_at_1i" name="post[#{id}][updated_at(1i)]">\n} + expected = %{<select id="post_456_updated_at_1i" name="post[#{id}][updated_at(1i)]">\n}.dup expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -3059,7 +3083,7 @@ class DateHelperTest < ActionView::TestCase @post.updated_at = Time.local(2004, 6, 15, 16, 35) id = @post.id - expected = %{<select id="post_123_updated_at_1i" name="post[#{id}][updated_at(1i)]">\n} + expected = %{<select id="post_123_updated_at_1i" name="post[#{id}][updated_at(1i)]">\n}.dup expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -3088,7 +3112,7 @@ class DateHelperTest < ActionView::TestCase @post = Post.new @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35) - expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n} + expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}.dup 1999.upto(2009) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 2004}>#{i}</option>\n) } expected << "</select>\n" expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n} @@ -3112,14 +3136,14 @@ class DateHelperTest < ActionView::TestCase 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 35}>#{sprintf("%02d", i)}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, datetime_select("post", "updated_at", :include_seconds => true) + assert_dom_equal expected, datetime_select("post", "updated_at", include_seconds: true) end def test_datetime_select_discard_year @post = Post.new @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35) - expected = %{<input type="hidden" id="post_updated_at_1i" name="post[updated_at(1i)]" value="2004" />\n} + expected = %{<input type="hidden" id="post_updated_at_1i" name="post[updated_at(1i)]" value="2004" />\n}.dup expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n} 1.upto(12) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 6}>#{Date::MONTHNAMES[i]}</option>\n) } expected << "</select>\n" @@ -3137,14 +3161,14 @@ class DateHelperTest < ActionView::TestCase 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, datetime_select("post", "updated_at", :discard_year => true) + assert_dom_equal expected, datetime_select("post", "updated_at", discard_year: true) end def test_datetime_select_discard_month @post = Post.new @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35) - expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n} + expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}.dup 1999.upto(2009) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 2004}>#{i}</option>\n) } expected << "</select>\n" expected << %{<input type="hidden" id="post_updated_at_2i" name="post[updated_at(2i)]" value="6" />\n} @@ -3160,14 +3184,14 @@ class DateHelperTest < ActionView::TestCase 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, datetime_select("post", "updated_at", :discard_month => true) + assert_dom_equal expected, datetime_select("post", "updated_at", discard_month: true) end def test_datetime_select_discard_year_and_month @post = Post.new @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35) - expected = %{<input type="hidden" id="post_updated_at_1i" name="post[updated_at(1i)]" value="2004" />\n} + expected = %{<input type="hidden" id="post_updated_at_1i" name="post[updated_at(1i)]" value="2004" />\n}.dup expected << %{<input type="hidden" id="post_updated_at_2i" name="post[updated_at(2i)]" value="6" />\n} expected << %{<input type="hidden" id="post_updated_at_3i" name="post[updated_at(3i)]" value="1" />\n} @@ -3179,14 +3203,14 @@ class DateHelperTest < ActionView::TestCase 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, datetime_select("post", "updated_at", :discard_year => true, :discard_month => true) + assert_dom_equal expected, datetime_select("post", "updated_at", discard_year: true, discard_month: true) end def test_datetime_select_discard_year_and_month_with_disabled_html_option @post = Post.new @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35) - expected = %{<input type="hidden" id="post_updated_at_1i" disabled="disabled" name="post[updated_at(1i)]" value="2004" />\n} + expected = %{<input type="hidden" id="post_updated_at_1i" disabled="disabled" name="post[updated_at(1i)]" value="2004" />\n}.dup expected << %{<input type="hidden" id="post_updated_at_2i" disabled="disabled" name="post[updated_at(2i)]" value="6" />\n} expected << %{<input type="hidden" id="post_updated_at_3i" disabled="disabled" name="post[updated_at(3i)]" value="1" />\n} @@ -3198,14 +3222,14 @@ class DateHelperTest < ActionView::TestCase 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, datetime_select("post", "updated_at", { :discard_year => true, :discard_month => true }, :disabled => true) + assert_dom_equal expected, datetime_select("post", "updated_at", { discard_year: true, discard_month: true }, { disabled: true }) end def test_datetime_select_discard_hour @post = Post.new @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35) - expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n} + expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}.dup 1999.upto(2009) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 2004}>#{i}</option>\n) } expected << "</select>\n" expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n} @@ -3215,14 +3239,14 @@ class DateHelperTest < ActionView::TestCase 1.upto(31) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 15}>#{i}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, datetime_select("post", "updated_at", :discard_hour => true) + assert_dom_equal expected, datetime_select("post", "updated_at", discard_hour: true) end def test_datetime_select_discard_minute @post = Post.new @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35) - expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n} + expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}.dup 1999.upto(2009) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 2004}>#{i}</option>\n) } expected << "</select>\n" expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n} @@ -3239,14 +3263,14 @@ class DateHelperTest < ActionView::TestCase expected << "</select>\n" expected << %{<input type="hidden" id="post_updated_at_5i" name="post[updated_at(5i)]" value="16" />\n} - assert_dom_equal expected, datetime_select("post", "updated_at", :discard_minute => true) + assert_dom_equal expected, datetime_select("post", "updated_at", discard_minute: true) end def test_datetime_select_disabled_and_discard_minute @post = Post.new @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35) - expected = %{<select id="post_updated_at_1i" disabled="disabled" name="post[updated_at(1i)]">\n} + expected = %{<select id="post_updated_at_1i" disabled="disabled" name="post[updated_at(1i)]">\n}.dup 1999.upto(2009) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 2004}>#{i}</option>\n) } expected << "</select>\n" expected << %{<select id="post_updated_at_2i" disabled="disabled" name="post[updated_at(2i)]">\n} @@ -3263,14 +3287,14 @@ class DateHelperTest < ActionView::TestCase expected << "</select>\n" expected << %{<input type="hidden" id="post_updated_at_5i" disabled="disabled" name="post[updated_at(5i)]" value="16" />\n} - assert_dom_equal expected, datetime_select("post", "updated_at", :discard_minute => true, :disabled => true) + assert_dom_equal expected, datetime_select("post", "updated_at", discard_minute: true, disabled: true) end def test_datetime_select_invalid_order @post = Post.new @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35) - expected = %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n} + expected = %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n}.dup 1.upto(31) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 15}>#{i}</option>\n) } expected << "</select>\n" expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n} @@ -3290,14 +3314,14 @@ class DateHelperTest < ActionView::TestCase 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, datetime_select("post", "updated_at", :order => [:minute, :day, :hour, :month, :year, :second]) + assert_dom_equal expected, datetime_select("post", "updated_at", order: [:minute, :day, :hour, :month, :year, :second]) end def test_datetime_select_discard_with_order @post = Post.new @post.updated_at = Time.local(2004, 6, 15, 15, 16, 35) - expected = %{<input type="hidden" id="post_updated_at_1i" name="post[updated_at(1i)]" value="2004" />\n} + expected = %{<input type="hidden" id="post_updated_at_1i" name="post[updated_at(1i)]" value="2004" />\n}.dup expected << %{<select id="post_updated_at_3i" name="post[updated_at(3i)]">\n} 1.upto(31) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 15}>#{i}</option>\n) } expected << "</select>\n" @@ -3315,14 +3339,14 @@ class DateHelperTest < ActionView::TestCase 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, datetime_select("post", "updated_at", :order => [:day, :month]) + assert_dom_equal expected, datetime_select("post", "updated_at", order: [:day, :month]) end def test_datetime_select_with_default_value_as_time @post = Post.new @post.updated_at = nil - expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n} + expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}.dup 2001.upto(2011) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 2006}>#{i}</option>\n) } expected << "</select>\n" expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n} @@ -3342,14 +3366,14 @@ class DateHelperTest < ActionView::TestCase 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, datetime_select("post", "updated_at", :default => Time.local(2006, 9, 19, 15, 16, 35)) + assert_dom_equal expected, datetime_select("post", "updated_at", default: Time.local(2006, 9, 19, 15, 16, 35)) end def test_include_blank_overrides_default_option @post = Post.new @post.updated_at = nil - expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n} + expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}.dup expected << %(<option value=""></option>\n) (Time.now.year - 5).upto(Time.now.year + 5) { |i| expected << %(<option value="#{i}">#{i}</option>\n) } expected << "</select>\n" @@ -3362,14 +3386,14 @@ class DateHelperTest < ActionView::TestCase 1.upto(31) { |i| expected << %(<option value="#{i}">#{i}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, date_select("post", "updated_at", :default => Time.local(2006, 9, 19, 15, 16, 35), :include_blank => true) + assert_dom_equal expected, date_select("post", "updated_at", default: Time.local(2006, 9, 19, 15, 16, 35), include_blank: true) end def test_datetime_select_with_default_value_as_hash @post = Post.new @post.updated_at = nil - expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n} + expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]">\n}.dup (Time.now.year - 5).upto(Time.now.year + 5) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == Time.now.year}>#{i}</option>\n) } expected << "</select>\n" expected << %{<select id="post_updated_at_2i" name="post[updated_at(2i)]">\n} @@ -3389,14 +3413,14 @@ class DateHelperTest < ActionView::TestCase 0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 42}>#{sprintf("%02d", i)}</option>\n) } expected << "</select>\n" - assert_dom_equal expected, datetime_select("post", "updated_at", :default => { :month => 10, :minute => 42, :hour => 9 }) + assert_dom_equal expected, datetime_select("post", "updated_at", default: { month: 10, minute: 42, hour: 9 }) end def test_datetime_select_with_html_options @post = Post.new @post.updated_at = Time.local(2004, 6, 15, 16, 35) - expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]" class="selector">\n} + expected = %{<select id="post_updated_at_1i" name="post[updated_at(1i)]" class="selector">\n}.dup expected << %{<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option value="2004" selected="selected">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n} expected << "</select>\n" @@ -3418,7 +3442,7 @@ class DateHelperTest < ActionView::TestCase expected << %{<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">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" selected="selected">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, datetime_select("post", "updated_at", {}, :class => 'selector') + assert_dom_equal expected, datetime_select("post", "updated_at", {}, { class: "selector" }) end def test_date_select_should_not_change_passed_options_hash @@ -3426,24 +3450,24 @@ class DateHelperTest < ActionView::TestCase @post.updated_at = Time.local(2008, 7, 16, 23, 30) options = { - :order => [ :year, :month, :day ], - :default => { :year => 2008, :month => 7, :day => 16, :hour => 23, :minute => 30, :second => 1 }, - :discard_type => false, - :include_blank => false, - :ignore_date => false, - :include_seconds => true + order: [ :year, :month, :day ], + default: { year: 2008, month: 7, day: 16, hour: 23, minute: 30, second: 1 }, + discard_type: false, + include_blank: false, + ignore_date: false, + include_seconds: true } date_select(@post, :updated_at, options) # note: the literal hash is intentional to show that the actual options hash isn't modified # don't change this! assert_equal({ - :order => [ :year, :month, :day ], - :default => { :year => 2008, :month => 7, :day => 16, :hour => 23, :minute => 30, :second => 1 }, - :discard_type => false, - :include_blank => false, - :ignore_date => false, - :include_seconds => true + order: [ :year, :month, :day ], + default: { year: 2008, month: 7, day: 16, hour: 23, minute: 30, second: 1 }, + discard_type: false, + include_blank: false, + ignore_date: false, + include_seconds: true }, options) end @@ -3452,24 +3476,24 @@ class DateHelperTest < ActionView::TestCase @post.updated_at = Time.local(2008, 7, 16, 23, 30) options = { - :order => [ :year, :month, :day ], - :default => { :year => 2008, :month => 7, :day => 16, :hour => 23, :minute => 30, :second => 1 }, - :discard_type => false, - :include_blank => false, - :ignore_date => false, - :include_seconds => true + order: [ :year, :month, :day ], + default: { year: 2008, month: 7, day: 16, hour: 23, minute: 30, second: 1 }, + discard_type: false, + include_blank: false, + ignore_date: false, + include_seconds: true } datetime_select(@post, :updated_at, options) # note: the literal hash is intentional to show that the actual options hash isn't modified # don't change this! assert_equal({ - :order => [ :year, :month, :day ], - :default => { :year => 2008, :month => 7, :day => 16, :hour => 23, :minute => 30, :second => 1 }, - :discard_type => false, - :include_blank => false, - :ignore_date => false, - :include_seconds => true + order: [ :year, :month, :day ], + default: { year: 2008, month: 7, day: 16, hour: 23, minute: 30, second: 1 }, + discard_type: false, + include_blank: false, + ignore_date: false, + include_seconds: true }, options) end @@ -3478,93 +3502,93 @@ class DateHelperTest < ActionView::TestCase @post.updated_at = Time.local(2008, 7, 16, 23, 30) options = { - :order => [ :year, :month, :day ], - :default => { :year => 2008, :month => 7, :day => 16, :hour => 23, :minute => 30, :second => 1 }, - :discard_type => false, - :include_blank => false, - :ignore_date => false, - :include_seconds => true + order: [ :year, :month, :day ], + default: { year: 2008, month: 7, day: 16, hour: 23, minute: 30, second: 1 }, + discard_type: false, + include_blank: false, + ignore_date: false, + include_seconds: true } time_select(@post, :updated_at, options) # note: the literal hash is intentional to show that the actual options hash isn't modified # don't change this! assert_equal({ - :order => [ :year, :month, :day ], - :default => { :year => 2008, :month => 7, :day => 16, :hour => 23, :minute => 30, :second => 1 }, - :discard_type => false, - :include_blank => false, - :ignore_date => false, - :include_seconds => true + order: [ :year, :month, :day ], + default: { year: 2008, month: 7, day: 16, hour: 23, minute: 30, second: 1 }, + discard_type: false, + include_blank: false, + ignore_date: false, + include_seconds: true }, options) end def test_select_date_should_not_change_passed_options_hash options = { - :order => [ :year, :month, :day ], - :default => { :year => 2008, :month => 7, :day => 16, :hour => 23, :minute => 30, :second => 1 }, - :discard_type => false, - :include_blank => false, - :ignore_date => false, - :include_seconds => true + order: [ :year, :month, :day ], + default: { year: 2008, month: 7, day: 16, hour: 23, minute: 30, second: 1 }, + discard_type: false, + include_blank: false, + ignore_date: false, + include_seconds: true } select_date(Date.today, options) # note: the literal hash is intentional to show that the actual options hash isn't modified # don't change this! assert_equal({ - :order => [ :year, :month, :day ], - :default => { :year => 2008, :month => 7, :day => 16, :hour => 23, :minute => 30, :second => 1 }, - :discard_type => false, - :include_blank => false, - :ignore_date => false, - :include_seconds => true + order: [ :year, :month, :day ], + default: { year: 2008, month: 7, day: 16, hour: 23, minute: 30, second: 1 }, + discard_type: false, + include_blank: false, + ignore_date: false, + include_seconds: true }, options) end def test_select_datetime_should_not_change_passed_options_hash options = { - :order => [ :year, :month, :day ], - :default => { :year => 2008, :month => 7, :day => 16, :hour => 23, :minute => 30, :second => 1 }, - :discard_type => false, - :include_blank => false, - :ignore_date => false, - :include_seconds => true + order: [ :year, :month, :day ], + default: { year: 2008, month: 7, day: 16, hour: 23, minute: 30, second: 1 }, + discard_type: false, + include_blank: false, + ignore_date: false, + include_seconds: true } select_datetime(Time.now, options) # note: the literal hash is intentional to show that the actual options hash isn't modified # don't change this! assert_equal({ - :order => [ :year, :month, :day ], - :default => { :year => 2008, :month => 7, :day => 16, :hour => 23, :minute => 30, :second => 1 }, - :discard_type => false, - :include_blank => false, - :ignore_date => false, - :include_seconds => true + order: [ :year, :month, :day ], + default: { year: 2008, month: 7, day: 16, hour: 23, minute: 30, second: 1 }, + discard_type: false, + include_blank: false, + ignore_date: false, + include_seconds: true }, options) end def test_select_time_should_not_change_passed_options_hash options = { - :order => [ :year, :month, :day ], - :default => { :year => 2008, :month => 7, :day => 16, :hour => 23, :minute => 30, :second => 1 }, - :discard_type => false, - :include_blank => false, - :ignore_date => false, - :include_seconds => true + order: [ :year, :month, :day ], + default: { year: 2008, month: 7, day: 16, hour: 23, minute: 30, second: 1 }, + discard_type: false, + include_blank: false, + ignore_date: false, + include_seconds: true } select_time(Time.now, options) # note: the literal hash is intentional to show that the actual options hash isn't modified # don't change this! assert_equal({ - :order => [ :year, :month, :day ], - :default => { :year => 2008, :month => 7, :day => 16, :hour => 23, :minute => 30, :second => 1 }, - :discard_type => false, - :include_blank => false, - :ignore_date => false, - :include_seconds => true + order: [ :year, :month, :day ], + default: { year: 2008, month: 7, day: 16, hour: 23, minute: 30, second: 1 }, + discard_type: false, + include_blank: false, + ignore_date: false, + include_seconds: true }, options) end @@ -3575,19 +3599,19 @@ class DateHelperTest < ActionView::TestCase assert select_minute(Time.mktime(2003, 8, 16, 8, 4, 18)).html_safe? assert select_second(Time.mktime(2003, 8, 16, 8, 4, 18)).html_safe? - assert select_minute(8, :use_hidden => true).html_safe? - assert select_month(8, :prompt => 'Choose month').html_safe? + assert select_minute(8, use_hidden: true).html_safe? + assert select_month(8, prompt: "Choose month").html_safe? - assert select_time(Time.mktime(2003, 8, 16, 8, 4, 18), {}, :class => 'selector').html_safe? - assert select_date(Time.mktime(2003, 8, 16), :date_separator => " / ", :start_year => 2003, :end_year => 2005, :prefix => "date[first]").html_safe? + assert select_time(Time.mktime(2003, 8, 16, 8, 4, 18), {}, { class: "selector" }).html_safe? + assert select_date(Time.mktime(2003, 8, 16), date_separator: " / ", start_year: 2003, end_year: 2005, prefix: "date[first]").html_safe? end def test_object_select_html_safety @post = Post.new @post.written_on = Date.new(2004, 6, 15) - assert date_select("post", "written_on", :default => Time.local(2006, 9, 19, 15, 16, 35), :include_blank => true).html_safe? - assert time_select("post", "written_on", :ignore_date => true).html_safe? + assert date_select("post", "written_on", default: Time.local(2006, 9, 19, 15, 16, 35), include_blank: true).html_safe? + assert time_select("post", "written_on", ignore_date: true).html_safe? end def test_time_tag_with_date @@ -3597,26 +3621,22 @@ class DateHelperTest < ActionView::TestCase end def test_time_tag_with_time - time = Time.new(2013, 2, 20, 0, 0, 0, '+00:00') + time = Time.new(2013, 2, 20, 0, 0, 0, "+00:00") expected = '<time datetime="2013-02-20T00:00:00+00:00">February 20, 2013 00:00</time>' assert_equal expected, time_tag(time) end - def test_time_tag_pubdate_option - assert_match(/<time.*pubdate="pubdate">.*<\/time>/, time_tag(Time.now, :pubdate => true)) - end - def test_time_tag_with_given_text - assert_match(/<time.*>Right now<\/time>/, time_tag(Time.now, 'Right now')) + assert_match(/<time.*>Right now<\/time>/, time_tag(Time.now, "Right now")) end def test_time_tag_with_given_block - assert_match(/<time.*><span>Right now<\/span><\/time>/, time_tag(Time.now){ raw('<span>Right now</span>') }) + assert_match(/<time.*><span>Right now<\/span><\/time>/, time_tag(Time.now) { raw("<span>Right now</span>") }) end def test_time_tag_with_different_format - time = Time.new(2013, 2, 20, 0, 0, 0, '+00:00') + time = Time.new(2013, 2, 20, 0, 0, 0, "+00:00") expected = '<time datetime="2013-02-20T00:00:00+00:00">20 Feb 00:00</time>' - assert_equal expected, time_tag(time, :format => :short) + assert_equal expected, time_tag(time, format: :short) end end diff --git a/actionview/test/template/dependency_tracker_test.rb b/actionview/test/template/dependency_tracker_test.rb index 3ece9e50cd..ef7aeac039 100644 --- a/actionview/test/template/dependency_tracker_test.rb +++ b/actionview/test/template/dependency_tracker_test.rb @@ -1,5 +1,7 @@ -require 'abstract_unit' -require 'action_view/dependency_tracker' +# frozen_string_literal: true + +require "abstract_unit" +require "action_view/dependency_tracker" class NeckbeardTracker def self.call(name, template) @@ -15,8 +17,8 @@ class FakeTemplate end end -Neckbeard = lambda {|template| template.source } -Bowtie = lambda {|template| template.source } +Neckbeard = lambda { |template| template.source } +Bowtie = lambda { |template| template.source } class DependencyTrackerTest < ActionView::TestCase def tracker diff --git a/actionview/test/template/digestor_test.rb b/actionview/test/template/digestor_test.rb index d4c5048bde..1bfa39a319 100644 --- a/actionview/test/template/digestor_test.rb +++ b/actionview/test/template/digestor_test.rb @@ -1,23 +1,21 @@ -require 'abstract_unit' -require 'fileutils' -require 'action_view/dependency_tracker' +# frozen_string_literal: true -class FixtureTemplate - attr_reader :source, :handler - - def initialize(template_path) - @source = File.read(template_path) - @handler = ActionView::Template.handler_for_extension(:erb) - rescue Errno::ENOENT - raise ActionView::MissingTemplate.new([], "", [], true, []) - end -end +require "abstract_unit" +require "fileutils" +require "action_view/dependency_tracker" class FixtureFinder < ActionView::LookupContext - FIXTURES_DIR = "#{File.dirname(__FILE__)}/../fixtures/digestor" + FIXTURES_DIR = File.expand_path("../fixtures/digestor", __dir__) def initialize(details = {}) - super(ActionView::PathSet.new(['digestor']), details, []) + super(ActionView::PathSet.new(["digestor", "digestor/api"]), details, []) + @rendered_format = :html + end +end + +class ActionView::Digestor::Node + def flatten + [self] + children.flat_map(&:flatten) end end @@ -61,25 +59,21 @@ class TemplateDigestorTest < ActionView::TestCase 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") + disable_resolver_caching do + assert_digest_difference("events/index") do + add_template("events/_uncompleted") + end 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") + disable_resolver_caching do + add_template("events/_subscribers_changed") - assert_digest_difference("events/index") do - remove_template("events/_subscribers_changed") + assert_digest_difference("events/index") do + remove_template("events/_subscribers_changed") + end end - ensure - ActionView::Resolver.caching = old_caching end def test_second_level_dependency @@ -119,25 +113,25 @@ class TemplateDigestorTest < ActionView::TestCase end def test_logging_of_missing_template_for_dependencies - assert_logged "'messages/something_missing' file doesn't exist, so no dependencies" do + assert_logged "Couldn't find template for digesting: messages/something_missing" 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 + assert_logged "Couldn't find template for digesting: messages/something_missing" do nested_dependencies("messages/something_missing") end end def test_getting_of_singly_nested_dependencies singly_nested_dependencies = ["messages/header", "messages/form", "messages/message", "events/event", "comments/comment"] - assert_equal singly_nested_dependencies, nested_dependencies('messages/edit') + assert_equal singly_nested_dependencies, nested_dependencies("messages/edit") end def test_getting_of_doubly_nested_dependencies - doubly_nested = [{"comments/comments"=>["comments/comment"]}, "messages/message"] - assert_equal doubly_nested, nested_dependencies('messages/peek') + doubly_nested = [{ "comments/comments" => ["comments/comment"] }, "messages/message"] + assert_equal doubly_nested, nested_dependencies("messages/peek") end def test_nested_template_directory @@ -147,10 +141,25 @@ class TemplateDigestorTest < ActionView::TestCase end def test_nested_template_deps - nested_deps = ["messages/header", {"comments/comments"=>["comments/comment"]}, "messages/actions/move", "events/event", "messages/something_missing", "messages/something_missing_1", "messages/message", "messages/form"] + nested_deps = ["messages/header", { "comments/comments" => ["comments/comment"] }, "messages/actions/move", "events/event", "messages/something_missing", "messages/something_missing_1", "messages/message", "messages/form"] assert_equal nested_deps, nested_dependencies("messages/show") end + def test_nested_template_deps_with_non_default_rendered_format + finder.rendered_format = nil + nested_deps = [{ "comments/comments" => ["comments/comment"] }] + assert_equal nested_deps, nested_dependencies("messages/thread") + end + + def test_template_formats_of_nested_deps_with_non_default_rendered_format + finder.rendered_format = nil + assert_equal [:json], tree_template_formats("messages/thread").uniq + end + + def test_template_formats_of_dependencies_with_same_logical_name_and_different_rendered_format + assert_equal [:html], tree_template_formats("messages/show").uniq + end + def test_recursion_in_renders assert digest("level/recursion") # assert recursion is possible assert_not_nil digest("level/recursion") # assert digest is stored @@ -177,7 +186,7 @@ class TemplateDigestorTest < ActionView::TestCase end def test_dont_generate_a_digest_for_missing_templates - assert_equal '', digest("nothing/there") + assert_equal "", digest("nothing/there") end def test_collection_dependency @@ -198,7 +207,7 @@ class TemplateDigestorTest < ActionView::TestCase def test_details_are_included_in_cache_key # Cache the template digest. - @finder = FixtureFinder.new({:formats => [:html]}) + @finder = FixtureFinder.new(formats: [:html]) old_digest = digest("events/_event") # Change the template; the cached digest remains unchanged. @@ -262,6 +271,13 @@ class TemplateDigestorTest < ActionView::TestCase assert_not_equal digest_phone, digest_fridge_phone end + def test_different_formats_with_same_logical_template_names_results_in_different_digests + html_digest = digest("comments/_comment", format: :html) + json_digest = digest("comments/_comment", format: :json) + + assert_not_equal html_digest, json_digest + end + def test_digest_cache_cleanup_with_recursion first_digest = digest("level/_recursion") second_digest = digest("level/_recursion") @@ -273,21 +289,17 @@ class TemplateDigestorTest < ActionView::TestCase end def test_digest_cache_cleanup_with_recursion_and_template_caching_off - resolver_before = ActionView::Resolver.caching - ActionView::Resolver.caching = false + disable_resolver_caching do + first_digest = digest("level/_recursion") + second_digest = digest("level/_recursion") - first_digest = digest("level/_recursion") - second_digest = digest("level/_recursion") + assert first_digest - assert first_digest - - # If the cache is cleaned up correctly, subsequent digests should return the same - assert_equal first_digest, second_digest - ensure - ActionView::Resolver.caching = resolver_before + # If the cache is cleaned up correctly, subsequent digests should return the same + assert_equal first_digest, second_digest + end end - private def assert_logged(message) old_logger = ActionView::Base.logger @@ -316,8 +328,11 @@ class TemplateDigestorTest < ActionView::TestCase def digest(template_name, options = {}) options = options.dup + finder_options = options.extract!(:variants, :format) + + finder.variants = finder_options[:variants] || [] + finder.rendered_format = finder_options[:format] if finder_options[:format] - finder.variants = options.delete(:variants) || [] ActionView::Digestor.digest(name: template_name, finder: finder, dependencies: (options[:dependencies] || [])) end @@ -331,6 +346,18 @@ class TemplateDigestorTest < ActionView::TestCase tree.children.map(&:to_dep_map) end + def tree_template_formats(template_name) + tree = ActionView::Digestor.tree(template_name, finder) + tree.flatten.map(&:template).compact.flat_map(&:formats) + end + + def disable_resolver_caching + old_caching, ActionView::Resolver.caching = ActionView::Resolver.caching, false + yield + ensure + ActionView::Resolver.caching = old_caching + end + def finder @finder ||= FixtureFinder.new end diff --git a/actionview/test/template/erb/form_for_test.rb b/actionview/test/template/erb/form_for_test.rb index e722b40a9a..b6ecf003a5 100644 --- a/actionview/test/template/erb/form_for_test.rb +++ b/actionview/test/template/erb/form_for_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "abstract_unit" require "template/erb/helper" diff --git a/actionview/test/template/erb/helper.rb b/actionview/test/template/erb/helper.rb index a1973068d5..57d6cb1be3 100644 --- a/actionview/test/template/erb/helper.rb +++ b/actionview/test/template/erb/helper.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ERBTest class ViewContext include ActionView::Helpers::UrlHelper @@ -14,7 +16,7 @@ module ERBTest class BlockTestCase < ActiveSupport::TestCase def render_content(start, inside) template = block_helper(start, inside) - ActionView::Template::Handlers::Erubis.new(template).evaluate(ViewContext.new) + ActionView::Template::Handlers::ERB.erb_implementation.new(template).evaluate(ViewContext.new) end def block_helper(str, rest) diff --git a/actionview/test/template/erb/tag_helper_test.rb b/actionview/test/template/erb/tag_helper_test.rb index 84e328d8be..24a7592950 100644 --- a/actionview/test/template/erb/tag_helper_test.rb +++ b/actionview/test/template/erb/tag_helper_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "abstract_unit" require "template/erb/helper" @@ -18,8 +20,8 @@ module ERBTest end test "percent equals works with form tags" do - expected_output = %r{<form.*action="foo".*method="post">.*hello*</form>} - assert_match expected_output, render_content("form_tag('foo')", "<%= 'hello' %>") + expected_output = %r{<form.*action="/foo".*method="post">.*hello*</form>} + assert_match expected_output, render_content("form_tag('/foo')", "<%= 'hello' %>") end test "percent equals works with fieldset tags" do diff --git a/actionview/test/template/erb_util_test.rb b/actionview/test/template/erb_util_test.rb index 3e72be31de..8b804105f4 100644 --- a/actionview/test/template/erb_util_test.rb +++ b/actionview/test/template/erb_util_test.rb @@ -1,5 +1,7 @@ -require 'abstract_unit' -require 'active_support/json' +# frozen_string_literal: true + +require "abstract_unit" +require "active_support/json" class ErbUtilTest < ActiveSupport::TestCase include ERB::Util @@ -17,19 +19,19 @@ class ErbUtilTest < ActiveSupport::TestCase end HTML_ESCAPE_TEST_CASES = [ - ['<br>', '<br>'], - ['a & b', 'a & b'], - ['"quoted" string', '"quoted" string'], - ["'quoted' string", ''quoted' string'], + ["<br>", "<br>"], + ["a & b", "a & b"], + ['"quoted" string', ""quoted" string"], + ["'quoted' string", "'quoted' string"], [ '<script type="application/javascript">alert("You are \'pwned\'!")</script>', - '<script type="application/javascript">alert("You are 'pwned'!")</script>' + "<script type="application/javascript">alert("You are 'pwned'!")</script>" ] ] JSON_ESCAPE_TEST_CASES = [ - ['1', '1'], - ['null', 'null'], + ["1", "1"], + ["null", "null"], ['"&"', '"\u0026"'], ['"</script>"', '"\u003c/script\u003e"'], ['["</script>"]', '["\u003c/script\u003e"]'], @@ -51,7 +53,12 @@ class ErbUtilTest < ActiveSupport::TestCase def test_json_escape_does_not_alter_json_string_meaning JSON_ESCAPE_TEST_CASES.each do |(raw, _)| - assert_equal ActiveSupport::JSON.decode(raw), ActiveSupport::JSON.decode(json_escape(raw)) + expected = ActiveSupport::JSON.decode(raw) + if expected.nil? + assert_nil ActiveSupport::JSON.decode(json_escape(raw)) + else + assert_equal expected, ActiveSupport::JSON.decode(json_escape(raw)) + end end end @@ -91,17 +98,17 @@ class ErbUtilTest < ActiveSupport::TestCase end def test_html_escape_once - assert_equal '1 <>&"' 2 & 3', html_escape_once('1 <>&"\' 2 & 3') + assert_equal "1 <>&"' 2 & 3", html_escape_once('1 <>&"\' 2 & 3') assert_equal " ' ' λ λ " ' < > ", html_escape_once(" ' ' λ λ \" ' < > ") end def test_html_escape_once_returns_unsafe_strings_when_passed_unsafe_strings - value = html_escape_once('1 < 2 & 3') + value = html_escape_once("1 < 2 & 3") assert !value.html_safe? end def test_html_escape_once_returns_safe_strings_when_passed_safe_strings - value = html_escape_once('1 < 2 & 3'.html_safe) + value = html_escape_once("1 < 2 & 3".html_safe) assert value.html_safe? end end diff --git a/actionview/test/template/form_collections_helper_test.rb b/actionview/test/template/form_collections_helper_test.rb index 4f7ea88169..6db55a1447 100644 --- a/actionview/test/template/form_collections_helper_test.rb +++ b/actionview/test/template/form_collections_helper_test.rb @@ -1,11 +1,12 @@ -require 'abstract_unit' +# frozen_string_literal: true -class Category < Struct.new(:id, :name) -end +require "abstract_unit" + +Category = Struct.new(:id, :name) class FormCollectionsHelperTest < ActionView::TestCase def assert_no_select(selector, value = nil) - assert_select(selector, :text => value, :count => 0) + assert_select(selector, text: value, count: 0) end def with_collection_radio_buttons(*args, &block) @@ -17,170 +18,177 @@ class FormCollectionsHelperTest < ActionView::TestCase end # COLLECTION RADIO BUTTONS - test 'collection radio accepts a collection and generates inputs from value method' do + test "collection radio accepts a collection and generates inputs from value method" do with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s - assert_select 'input[type=radio][value=true]#user_active_true' - assert_select 'input[type=radio][value=false]#user_active_false' + assert_select "input[type=radio][value=true]#user_active_true" + assert_select "input[type=radio][value=false]#user_active_false" end - test 'collection radio accepts a collection and generates inputs from label method' do + test "collection radio accepts a collection and generates inputs from label method" do with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s - assert_select 'label[for=user_active_true]', 'true' - assert_select 'label[for=user_active_false]', 'false' + assert_select "label[for=user_active_true]", "true" + assert_select "label[for=user_active_false]", "false" + end + + test "collection radio handles camelized collection values for labels correctly" do + with_collection_radio_buttons :user, :active, ["Yes", "No"], :to_s, :to_s + + assert_select "label[for=user_active_yes]", "Yes" + assert_select "label[for=user_active_no]", "No" end - test 'collection radio handles camelized collection values for labels correctly' do - with_collection_radio_buttons :user, :active, ['Yes', 'No'], :to_s, :to_s + test "collection radio generates labels for non-English values correctly" do + with_collection_radio_buttons :user, :title, ["Господин", "Госпожа"], :to_s, :to_s - assert_select 'label[for=user_active_yes]', 'Yes' - assert_select 'label[for=user_active_no]', 'No' + assert_select "input[type=radio]#user_title_господин" + assert_select "label[for=user_title_господин]", "Господин" end - test 'collection radio should sanitize collection values for labels correctly' do - with_collection_radio_buttons :user, :name, ['$0.99', '$1.99'], :to_s, :to_s - assert_select 'label[for=user_name_099]', '$0.99' - assert_select 'label[for=user_name_199]', '$1.99' + test "collection radio should sanitize collection values for labels correctly" do + with_collection_radio_buttons :user, :name, ["$0.99", "$1.99"], :to_s, :to_s + assert_select "label[for=user_name_099]", "$0.99" + assert_select "label[for=user_name_199]", "$1.99" end - test 'collection radio accepts checked item' do - with_collection_radio_buttons :user, :active, [[1, true], [0, false]], :last, :first, :checked => true + test "collection radio accepts checked item" do + with_collection_radio_buttons :user, :active, [[1, true], [0, false]], :last, :first, checked: true - assert_select 'input[type=radio][value=true][checked=checked]' - assert_no_select 'input[type=radio][value=false][checked=checked]' + assert_select "input[type=radio][value=true][checked=checked]" + assert_no_select "input[type=radio][value=false][checked=checked]" end - test 'collection radio accepts multiple disabled items' do - collection = [[1, true], [0, false], [2, 'other']] - with_collection_radio_buttons :user, :active, collection, :last, :first, :disabled => [true, false] + test "collection radio accepts multiple disabled items" do + collection = [[1, true], [0, false], [2, "other"]] + with_collection_radio_buttons :user, :active, collection, :last, :first, disabled: [true, false] - assert_select 'input[type=radio][value=true][disabled=disabled]' - assert_select 'input[type=radio][value=false][disabled=disabled]' - assert_no_select 'input[type=radio][value=other][disabled=disabled]' + assert_select "input[type=radio][value=true][disabled=disabled]" + assert_select "input[type=radio][value=false][disabled=disabled]" + assert_no_select "input[type=radio][value=other][disabled=disabled]" end - test 'collection radio accepts single disabled item' do + test "collection radio accepts single disabled item" do collection = [[1, true], [0, false]] - with_collection_radio_buttons :user, :active, collection, :last, :first, :disabled => true + with_collection_radio_buttons :user, :active, collection, :last, :first, disabled: true - assert_select 'input[type=radio][value=true][disabled=disabled]' - assert_no_select 'input[type=radio][value=false][disabled=disabled]' + assert_select "input[type=radio][value=true][disabled=disabled]" + assert_no_select "input[type=radio][value=false][disabled=disabled]" end - test 'collection radio accepts multiple readonly items' do - collection = [[1, true], [0, false], [2, 'other']] - with_collection_radio_buttons :user, :active, collection, :last, :first, :readonly => [true, false] + test "collection radio accepts multiple readonly items" do + collection = [[1, true], [0, false], [2, "other"]] + with_collection_radio_buttons :user, :active, collection, :last, :first, readonly: [true, false] - assert_select 'input[type=radio][value=true][readonly=readonly]' - assert_select 'input[type=radio][value=false][readonly=readonly]' - assert_no_select 'input[type=radio][value=other][readonly=readonly]' + assert_select "input[type=radio][value=true][readonly=readonly]" + assert_select "input[type=radio][value=false][readonly=readonly]" + assert_no_select "input[type=radio][value=other][readonly=readonly]" end - test 'collection radio accepts single readonly item' do + test "collection radio accepts single readonly item" do collection = [[1, true], [0, false]] - with_collection_radio_buttons :user, :active, collection, :last, :first, :readonly => true + with_collection_radio_buttons :user, :active, collection, :last, :first, readonly: true - assert_select 'input[type=radio][value=true][readonly=readonly]' - assert_no_select 'input[type=radio][value=false][readonly=readonly]' + assert_select "input[type=radio][value=true][readonly=readonly]" + assert_no_select "input[type=radio][value=false][readonly=readonly]" end - test 'collection radio accepts html options as input' do + test "collection radio accepts html options as input" do collection = [[1, true], [0, false]] - with_collection_radio_buttons :user, :active, collection, :last, :first, {}, :class => 'special-radio' + with_collection_radio_buttons :user, :active, collection, :last, :first, {}, { class: "special-radio" } - assert_select 'input[type=radio][value=true].special-radio#user_active_true' - assert_select 'input[type=radio][value=false].special-radio#user_active_false' + assert_select "input[type=radio][value=true].special-radio#user_active_true" + assert_select "input[type=radio][value=false].special-radio#user_active_false" end - test 'collection radio accepts html options as the last element of array' do - collection = [[1, true, {class: 'foo'}], [0, false, {class: 'bar'}]] + test "collection radio accepts html options as the last element of array" do + collection = [[1, true, { class: "foo" }], [0, false, { class: "bar" }]] with_collection_radio_buttons :user, :active, collection, :second, :first - assert_select 'input[type=radio][value=true].foo#user_active_true' - assert_select 'input[type=radio][value=false].bar#user_active_false' + assert_select "input[type=radio][value=true].foo#user_active_true" + assert_select "input[type=radio][value=false].bar#user_active_false" end - test 'collection radio sets the label class defined inside the block' do - collection = [[1, true, {class: 'foo'}], [0, false, {class: 'bar'}]] + test "collection radio sets the label class defined inside the block" do + collection = [[1, true, { class: "foo" }], [0, false, { class: "bar" }]] with_collection_radio_buttons :user, :active, collection, :second, :first do |b| b.label(class: "collection_radio_buttons") end - assert_select 'label.collection_radio_buttons[for=user_active_true]' - assert_select 'label.collection_radio_buttons[for=user_active_false]' + assert_select "label.collection_radio_buttons[for=user_active_true]" + assert_select "label.collection_radio_buttons[for=user_active_false]" end - test 'collection radio does not include the input class in the respective label' do - collection = [[1, true, {class: 'foo'}], [0, false, {class: 'bar'}]] + test "collection radio does not include the input class in the respective label" do + collection = [[1, true, { class: "foo" }], [0, false, { class: "bar" }]] with_collection_radio_buttons :user, :active, collection, :second, :first - assert_no_select 'label.foo[for=user_active_true]' - assert_no_select 'label.bar[for=user_active_false]' + assert_no_select "label.foo[for=user_active_true]" + assert_no_select "label.bar[for=user_active_false]" end - test 'collection radio does not wrap input inside the label' do + test "collection radio does not wrap input inside the label" do with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s - assert_select 'input[type=radio] + label' - assert_no_select 'label input' + assert_select "input[type=radio] + label" + assert_no_select "label input" end - test 'collection radio accepts a block to render the label as radio button wrapper' do + test "collection radio accepts a block to render the label as radio button wrapper" do with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s do |b| b.label { b.radio_button } end - assert_select 'label[for=user_active_true] > input#user_active_true[type=radio]' - assert_select 'label[for=user_active_false] > input#user_active_false[type=radio]' + assert_select "label[for=user_active_true] > input#user_active_true[type=radio]" + assert_select "label[for=user_active_false] > input#user_active_false[type=radio]" end - test 'collection radio accepts a block to change the order of label and radio button' do + test "collection radio accepts a block to change the order of label and radio button" do with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s do |b| b.label + b.radio_button end - assert_select 'label[for=user_active_true] + input#user_active_true[type=radio]' - assert_select 'label[for=user_active_false] + input#user_active_false[type=radio]' + assert_select "label[for=user_active_true] + input#user_active_true[type=radio]" + assert_select "label[for=user_active_false] + input#user_active_false[type=radio]" end - test 'collection radio with block helpers accept extra html options' do + test "collection radio with block helpers accept extra html options" do with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s do |b| - b.label(:class => "radio_button") + b.radio_button(:class => "radio_button") + b.label(class: "radio_button") + b.radio_button(class: "radio_button") end - assert_select 'label.radio_button[for=user_active_true] + input#user_active_true.radio_button[type=radio]' - assert_select 'label.radio_button[for=user_active_false] + input#user_active_false.radio_button[type=radio]' + assert_select "label.radio_button[for=user_active_true] + input#user_active_true.radio_button[type=radio]" + assert_select "label.radio_button[for=user_active_false] + input#user_active_false.radio_button[type=radio]" end - test 'collection radio with block helpers allows access to current text and value' do + test "collection radio with block helpers allows access to current text and value" do with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s do |b| - b.label(:"data-value" => b.value) { b.radio_button + b.text } + b.label("data-value": b.value) { b.radio_button + b.text } end - assert_select 'label[for=user_active_true][data-value=true]', 'true' do - assert_select 'input#user_active_true[type=radio]' + assert_select "label[for=user_active_true][data-value=true]", "true" do + assert_select "input#user_active_true[type=radio]" end - assert_select 'label[for=user_active_false][data-value=false]', 'false' do - assert_select 'input#user_active_false[type=radio]' + assert_select "label[for=user_active_false][data-value=false]", "false" do + assert_select "input#user_active_false[type=radio]" end end - test 'collection radio with block helpers allows access to the current object item in the collection to access extra properties' do + test "collection radio with block helpers allows access to the current object item in the collection to access extra properties" do with_collection_radio_buttons :user, :active, [true, false], :to_s, :to_s do |b| - b.label(:class => b.object) { b.radio_button + b.text } + b.label(class: b.object) { b.radio_button + b.text } end - assert_select 'label.true[for=user_active_true]', 'true' do - assert_select 'input#user_active_true[type=radio]' + assert_select "label.true[for=user_active_true]", "true" do + assert_select "input#user_active_true[type=radio]" end - assert_select 'label.false[for=user_active_false]', 'false' do - assert_select 'input#user_active_false[type=radio]' + assert_select "label.false[for=user_active_false]", "false" do + assert_select "input#user_active_false[type=radio]" end end - test 'collection radio buttons with fields for' do - collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')] + test "collection radio buttons with fields for" do + collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] @output_buffer = fields_for(:post) do |p| p.collection_radio_buttons :category_id, collection, :id, :name end @@ -188,186 +196,193 @@ class FormCollectionsHelperTest < ActionView::TestCase assert_select 'input#post_category_id_1[type=radio][value="1"]' assert_select 'input#post_category_id_2[type=radio][value="2"]' - assert_select 'label[for=post_category_id_1]', 'Category 1' - assert_select 'label[for=post_category_id_2]', 'Category 2' + assert_select "label[for=post_category_id_1]", "Category 1" + assert_select "label[for=post_category_id_2]", "Category 2" end - test 'collection radio accepts checked item which has a value of false' do - with_collection_radio_buttons :user, :active, [[1, true], [0, false]], :last, :first, :checked => false - assert_no_select 'input[type=radio][value=true][checked=checked]' - assert_select 'input[type=radio][value=false][checked=checked]' + test "collection radio accepts checked item which has a value of false" do + with_collection_radio_buttons :user, :active, [[1, true], [0, false]], :last, :first, checked: false + assert_no_select "input[type=radio][value=true][checked=checked]" + assert_select "input[type=radio][value=false][checked=checked]" end - test 'collection radio buttons generates only one hidden field for the entire collection, to ensure something will be sent back to the server when posting an empty collection' do - collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')] + test "collection radio buttons generates only one hidden field for the entire collection, to ensure something will be sent back to the server when posting an empty collection" do + collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] with_collection_radio_buttons :user, :category_ids, collection, :id, :name assert_select "input[type=hidden][name='user[category_ids]'][value='']", count: 1 end - test 'collection radio buttons generates a hidden field using the given :name in :html_options' do - collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')] + test "collection radio buttons generates a hidden field using the given :name in :html_options" do + collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] with_collection_radio_buttons :user, :category_ids, collection, :id, :name, {}, { name: "user[other_category_ids]" } assert_select "input[type=hidden][name='user[other_category_ids]'][value='']", count: 1 end - test 'collection radio buttons generates a hidden field with index if it was provided' do - collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')] - with_collection_radio_buttons :user, :category_ids, collection, :id, :name, { index: 322 } + test "collection radio buttons generates a hidden field with index if it was provided" do + collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] + with_collection_radio_buttons :user, :category_ids, collection, :id, :name, index: 322 assert_select "input[type=hidden][name='user[322][category_ids]'][value='']", count: 1 end - test 'collection radio buttons does not generate a hidden field if include_hidden option is false' do - collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')] + test "collection radio buttons does not generate a hidden field if include_hidden option is false" do + collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] with_collection_radio_buttons :user, :category_ids, collection, :id, :name, include_hidden: false assert_select "input[type=hidden][name='user[category_ids]'][value='']", count: 0 end - test 'collection radio buttons does not generate a hidden field if include_hidden option is false with key as string' do - collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')] - with_collection_radio_buttons :user, :category_ids, collection, :id, :name, 'include_hidden' => false + test "collection radio buttons does not generate a hidden field if include_hidden option is false with key as string" do + collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] + with_collection_radio_buttons :user, :category_ids, collection, :id, :name, "include_hidden" => false assert_select "input[type=hidden][name='user[category_ids]'][value='']", count: 0 end # COLLECTION CHECK BOXES - test 'collection check boxes accepts a collection and generate a series of checkboxes for value method' do - collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')] + test "collection check boxes accepts a collection and generate a series of checkboxes for value method" do + collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] with_collection_check_boxes :user, :category_ids, collection, :id, :name assert_select 'input#user_category_ids_1[type=checkbox][value="1"]' assert_select 'input#user_category_ids_2[type=checkbox][value="2"]' end - test 'collection check boxes generates only one hidden field for the entire collection, to ensure something will be sent back to the server when posting an empty collection' do - collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')] + test "collection check boxes generates only one hidden field for the entire collection, to ensure something will be sent back to the server when posting an empty collection" do + collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] with_collection_check_boxes :user, :category_ids, collection, :id, :name - assert_select "input[type=hidden][name='user[category_ids][]'][value='']", :count => 1 + assert_select "input[type=hidden][name='user[category_ids][]'][value='']", count: 1 end - test 'collection check boxes generates a hidden field using the given :name in :html_options' do - collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')] - with_collection_check_boxes :user, :category_ids, collection, :id, :name, {}, {name: "user[other_category_ids][]"} + test "collection check boxes generates a hidden field using the given :name in :html_options" do + collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] + with_collection_check_boxes :user, :category_ids, collection, :id, :name, {}, { name: "user[other_category_ids][]" } - assert_select "input[type=hidden][name='user[other_category_ids][]'][value='']", :count => 1 + assert_select "input[type=hidden][name='user[other_category_ids][]'][value='']", count: 1 end - test 'collection check boxes generates a hidden field with index if it was provided' do - collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')] - with_collection_check_boxes :user, :category_ids, collection, :id, :name, { index: 322 } + test "collection check boxes generates a hidden field with index if it was provided" do + collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] + with_collection_check_boxes :user, :category_ids, collection, :id, :name, index: 322 assert_select "input[type=hidden][name='user[322][category_ids][]'][value='']", count: 1 end - test 'collection check boxes does not generate a hidden field if include_hidden option is false' do - collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')] + test "collection check boxes does not generate a hidden field if include_hidden option is false" do + collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] with_collection_check_boxes :user, :category_ids, collection, :id, :name, include_hidden: false - assert_select "input[type=hidden][name='user[category_ids][]'][value='']", :count => 0 + assert_select "input[type=hidden][name='user[category_ids][]'][value='']", count: 0 end - test 'collection check boxes does not generate a hidden field if include_hidden option is false with key as string' do - collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')] - with_collection_check_boxes :user, :category_ids, collection, :id, :name, 'include_hidden' => false + test "collection check boxes does not generate a hidden field if include_hidden option is false with key as string" do + collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] + with_collection_check_boxes :user, :category_ids, collection, :id, :name, "include_hidden" => false assert_select "input[type=hidden][name='user[category_ids][]'][value='']", count: 0 end - test 'collection check boxes accepts a collection and generate a series of checkboxes with labels for label method' do - collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')] + test "collection check boxes accepts a collection and generate a series of checkboxes with labels for label method" do + collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] with_collection_check_boxes :user, :category_ids, collection, :id, :name - assert_select 'label[for=user_category_ids_1]', 'Category 1' - assert_select 'label[for=user_category_ids_2]', 'Category 2' + assert_select "label[for=user_category_ids_1]", "Category 1" + assert_select "label[for=user_category_ids_2]", "Category 2" end - test 'collection check boxes handles camelized collection values for labels correctly' do - with_collection_check_boxes :user, :active, ['Yes', 'No'], :to_s, :to_s + test "collection check boxes handles camelized collection values for labels correctly" do + with_collection_check_boxes :user, :active, ["Yes", "No"], :to_s, :to_s + + assert_select "label[for=user_active_yes]", "Yes" + assert_select "label[for=user_active_no]", "No" + end - assert_select 'label[for=user_active_yes]', 'Yes' - assert_select 'label[for=user_active_no]', 'No' + test "collection check box should sanitize collection values for labels correctly" do + with_collection_check_boxes :user, :name, ["$0.99", "$1.99"], :to_s, :to_s + assert_select "label[for=user_name_099]", "$0.99" + assert_select "label[for=user_name_199]", "$1.99" end - test 'collection check box should sanitize collection values for labels correctly' do - with_collection_check_boxes :user, :name, ['$0.99', '$1.99'], :to_s, :to_s - assert_select 'label[for=user_name_099]', '$0.99' - assert_select 'label[for=user_name_199]', '$1.99' + test "collection check boxes generates labels for non-English values correctly" do + with_collection_check_boxes :user, :title, ["Господин", "Госпожа"], :to_s, :to_s + + assert_select "input[type=checkbox]#user_title_господин" + assert_select "label[for=user_title_господин]", "Господин" end - test 'collection check boxes accepts html options as the last element of array' do - collection = [[1, 'Category 1', {class: 'foo'}], [2, 'Category 2', {class: 'bar'}]] + test "collection check boxes accepts html options as the last element of array" do + collection = [[1, "Category 1", { class: "foo" }], [2, "Category 2", { class: "bar" }]] with_collection_check_boxes :user, :active, collection, :first, :second assert_select 'input[type=checkbox][value="1"].foo' assert_select 'input[type=checkbox][value="2"].bar' end - test 'collection check boxes propagates input id to the label for attribute' do - collection = [[1, 'Category 1', {id: 'foo'}], [2, 'Category 2', {id: 'bar'}]] + test "collection check boxes propagates input id to the label for attribute" do + collection = [[1, "Category 1", { id: "foo" }], [2, "Category 2", { id: "bar" }]] with_collection_check_boxes :user, :active, collection, :first, :second assert_select 'input[type=checkbox][value="1"]#foo' assert_select 'input[type=checkbox][value="2"]#bar' - assert_select 'label[for=foo]' - assert_select 'label[for=bar]' + assert_select "label[for=foo]" + assert_select "label[for=bar]" end - test 'collection check boxes sets the label class defined inside the block' do - collection = [[1, 'Category 1', {class: 'foo'}], [2, 'Category 2', {class: 'bar'}]] + test "collection check boxes sets the label class defined inside the block" do + collection = [[1, "Category 1", { class: "foo" }], [2, "Category 2", { class: "bar" }]] with_collection_check_boxes :user, :active, collection, :second, :first do |b| - b.label(class: 'collection_check_boxes') + b.label(class: "collection_check_boxes") end - assert_select 'label.collection_check_boxes[for=user_active_category_1]' - assert_select 'label.collection_check_boxes[for=user_active_category_2]' + assert_select "label.collection_check_boxes[for=user_active_category_1]" + assert_select "label.collection_check_boxes[for=user_active_category_2]" end - test 'collection check boxes does not include the input class in the respective label' do - collection = [[1, 'Category 1', {class: 'foo'}], [2, 'Category 2', {class: 'bar'}]] + test "collection check boxes does not include the input class in the respective label" do + collection = [[1, "Category 1", { class: "foo" }], [2, "Category 2", { class: "bar" }]] with_collection_check_boxes :user, :active, collection, :second, :first - assert_no_select 'label.foo[for=user_active_category_1]' - assert_no_select 'label.bar[for=user_active_category_2]' + assert_no_select "label.foo[for=user_active_category_1]" + assert_no_select "label.bar[for=user_active_category_2]" end - test 'collection check boxes accepts selected values as :checked option' do - collection = (1..3).map{|i| [i, "Category #{i}"] } - with_collection_check_boxes :user, :category_ids, collection, :first, :last, :checked => [1, 3] + test "collection check boxes accepts selected values as :checked option" do + collection = (1..3).map { |i| [i, "Category #{i}"] } + with_collection_check_boxes :user, :category_ids, collection, :first, :last, checked: [1, 3] assert_select 'input[type=checkbox][value="1"][checked=checked]' assert_select 'input[type=checkbox][value="3"][checked=checked]' assert_no_select 'input[type=checkbox][value="2"][checked=checked]' end - test 'collection check boxes accepts selected string values as :checked option' do - collection = (1..3).map{|i| [i, "Category #{i}"] } - with_collection_check_boxes :user, :category_ids, collection, :first, :last, :checked => ['1', '3'] + test "collection check boxes accepts selected string values as :checked option" do + collection = (1..3).map { |i| [i, "Category #{i}"] } + with_collection_check_boxes :user, :category_ids, collection, :first, :last, checked: ["1", "3"] assert_select 'input[type=checkbox][value="1"][checked=checked]' assert_select 'input[type=checkbox][value="3"][checked=checked]' assert_no_select 'input[type=checkbox][value="2"][checked=checked]' end - test 'collection check boxes accepts a single checked value' do - collection = (1..3).map{|i| [i, "Category #{i}"] } - with_collection_check_boxes :user, :category_ids, collection, :first, :last, :checked => 3 + test "collection check boxes accepts a single checked value" do + collection = (1..3).map { |i| [i, "Category #{i}"] } + with_collection_check_boxes :user, :category_ids, collection, :first, :last, checked: 3 assert_select 'input[type=checkbox][value="3"][checked=checked]' assert_no_select 'input[type=checkbox][value="1"][checked=checked]' assert_no_select 'input[type=checkbox][value="2"][checked=checked]' end - test 'collection check boxes accepts selected values as :checked option and override the model values' do + test "collection check boxes accepts selected values as :checked option and override the model values" do user = Struct.new(:category_ids).new(2) - collection = (1..3).map{|i| [i, "Category #{i}"] } + collection = (1..3).map { |i| [i, "Category #{i}"] } @output_buffer = fields_for(:user, user) do |p| - p.collection_check_boxes :category_ids, collection, :first, :last, :checked => [1, 3] + p.collection_check_boxes :category_ids, collection, :first, :last, checked: [1, 3] end assert_select 'input[type=checkbox][value="1"][checked=checked]' @@ -375,70 +390,70 @@ class FormCollectionsHelperTest < ActionView::TestCase assert_no_select 'input[type=checkbox][value="2"][checked=checked]' end - test 'collection check boxes accepts multiple disabled items' do - collection = (1..3).map{|i| [i, "Category #{i}"] } - with_collection_check_boxes :user, :category_ids, collection, :first, :last, :disabled => [1, 3] + test "collection check boxes accepts multiple disabled items" do + collection = (1..3).map { |i| [i, "Category #{i}"] } + with_collection_check_boxes :user, :category_ids, collection, :first, :last, disabled: [1, 3] assert_select 'input[type=checkbox][value="1"][disabled=disabled]' assert_select 'input[type=checkbox][value="3"][disabled=disabled]' assert_no_select 'input[type=checkbox][value="2"][disabled=disabled]' end - test 'collection check boxes accepts single disabled item' do - collection = (1..3).map{|i| [i, "Category #{i}"] } - with_collection_check_boxes :user, :category_ids, collection, :first, :last, :disabled => 1 + test "collection check boxes accepts single disabled item" do + collection = (1..3).map { |i| [i, "Category #{i}"] } + with_collection_check_boxes :user, :category_ids, collection, :first, :last, disabled: 1 assert_select 'input[type=checkbox][value="1"][disabled=disabled]' assert_no_select 'input[type=checkbox][value="3"][disabled=disabled]' assert_no_select 'input[type=checkbox][value="2"][disabled=disabled]' end - test 'collection check boxes accepts a proc to disabled items' do - collection = (1..3).map{|i| [i, "Category #{i}"] } - with_collection_check_boxes :user, :category_ids, collection, :first, :last, :disabled => proc { |i| i.first == 1 } + test "collection check boxes accepts a proc to disabled items" do + collection = (1..3).map { |i| [i, "Category #{i}"] } + with_collection_check_boxes :user, :category_ids, collection, :first, :last, disabled: proc { |i| i.first == 1 } assert_select 'input[type=checkbox][value="1"][disabled=disabled]' assert_no_select 'input[type=checkbox][value="3"][disabled=disabled]' assert_no_select 'input[type=checkbox][value="2"][disabled=disabled]' end - test 'collection check boxes accepts multiple readonly items' do - collection = (1..3).map{|i| [i, "Category #{i}"] } - with_collection_check_boxes :user, :category_ids, collection, :first, :last, :readonly => [1, 3] + test "collection check boxes accepts multiple readonly items" do + collection = (1..3).map { |i| [i, "Category #{i}"] } + with_collection_check_boxes :user, :category_ids, collection, :first, :last, readonly: [1, 3] assert_select 'input[type=checkbox][value="1"][readonly=readonly]' assert_select 'input[type=checkbox][value="3"][readonly=readonly]' assert_no_select 'input[type=checkbox][value="2"][readonly=readonly]' end - test 'collection check boxes accepts single readonly item' do - collection = (1..3).map{|i| [i, "Category #{i}"] } - with_collection_check_boxes :user, :category_ids, collection, :first, :last, :readonly => 1 + test "collection check boxes accepts single readonly item" do + collection = (1..3).map { |i| [i, "Category #{i}"] } + with_collection_check_boxes :user, :category_ids, collection, :first, :last, readonly: 1 assert_select 'input[type=checkbox][value="1"][readonly=readonly]' assert_no_select 'input[type=checkbox][value="3"][readonly=readonly]' assert_no_select 'input[type=checkbox][value="2"][readonly=readonly]' end - test 'collection check boxes accepts a proc to readonly items' do - collection = (1..3).map{|i| [i, "Category #{i}"] } - with_collection_check_boxes :user, :category_ids, collection, :first, :last, :readonly => proc { |i| i.first == 1 } + test "collection check boxes accepts a proc to readonly items" do + collection = (1..3).map { |i| [i, "Category #{i}"] } + with_collection_check_boxes :user, :category_ids, collection, :first, :last, readonly: proc { |i| i.first == 1 } assert_select 'input[type=checkbox][value="1"][readonly=readonly]' assert_no_select 'input[type=checkbox][value="3"][readonly=readonly]' assert_no_select 'input[type=checkbox][value="2"][readonly=readonly]' end - test 'collection check boxes accepts html options' do - collection = [[1, 'Category 1'], [2, 'Category 2']] - with_collection_check_boxes :user, :category_ids, collection, :first, :last, {}, :class => 'check' + test "collection check boxes accepts html options" do + collection = [[1, "Category 1"], [2, "Category 2"]] + with_collection_check_boxes :user, :category_ids, collection, :first, :last, {}, { class: "check" } assert_select 'input.check[type=checkbox][value="1"]' assert_select 'input.check[type=checkbox][value="2"]' end - test 'collection check boxes with fields for' do - collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')] + test "collection check boxes with fields for" do + collection = [Category.new(1, "Category 1"), Category.new(2, "Category 2")] @output_buffer = fields_for(:post) do |p| p.collection_check_boxes :category_ids, collection, :id, :name end @@ -446,67 +461,67 @@ class FormCollectionsHelperTest < ActionView::TestCase assert_select 'input#post_category_ids_1[type=checkbox][value="1"]' assert_select 'input#post_category_ids_2[type=checkbox][value="2"]' - assert_select 'label[for=post_category_ids_1]', 'Category 1' - assert_select 'label[for=post_category_ids_2]', 'Category 2' + assert_select "label[for=post_category_ids_1]", "Category 1" + assert_select "label[for=post_category_ids_2]", "Category 2" end - test 'collection check boxes does not wrap input inside the label' do + test "collection check boxes does not wrap input inside the label" do with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s - assert_select 'input[type=checkbox] + label' - assert_no_select 'label input' + assert_select "input[type=checkbox] + label" + assert_no_select "label input" end - test 'collection check boxes accepts a block to render the label as check box wrapper' do + test "collection check boxes accepts a block to render the label as check box wrapper" do with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s do |b| b.label { b.check_box } end - assert_select 'label[for=user_active_true] > input#user_active_true[type=checkbox]' - assert_select 'label[for=user_active_false] > input#user_active_false[type=checkbox]' + assert_select "label[for=user_active_true] > input#user_active_true[type=checkbox]" + assert_select "label[for=user_active_false] > input#user_active_false[type=checkbox]" end - test 'collection check boxes accepts a block to change the order of label and check box' do + test "collection check boxes accepts a block to change the order of label and check box" do with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s do |b| b.label + b.check_box end - assert_select 'label[for=user_active_true] + input#user_active_true[type=checkbox]' - assert_select 'label[for=user_active_false] + input#user_active_false[type=checkbox]' + assert_select "label[for=user_active_true] + input#user_active_true[type=checkbox]" + assert_select "label[for=user_active_false] + input#user_active_false[type=checkbox]" end - test 'collection check boxes with block helpers accept extra html options' do + test "collection check boxes with block helpers accept extra html options" do with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s do |b| - b.label(:class => "check_box") + b.check_box(:class => "check_box") + b.label(class: "check_box") + b.check_box(class: "check_box") end - assert_select 'label.check_box[for=user_active_true] + input#user_active_true.check_box[type=checkbox]' - assert_select 'label.check_box[for=user_active_false] + input#user_active_false.check_box[type=checkbox]' + assert_select "label.check_box[for=user_active_true] + input#user_active_true.check_box[type=checkbox]" + assert_select "label.check_box[for=user_active_false] + input#user_active_false.check_box[type=checkbox]" end - test 'collection check boxes with block helpers allows access to current text and value' do + test "collection check boxes with block helpers allows access to current text and value" do with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s do |b| - b.label(:"data-value" => b.value) { b.check_box + b.text } + b.label("data-value": b.value) { b.check_box + b.text } end - assert_select 'label[for=user_active_true][data-value=true]', 'true' do - assert_select 'input#user_active_true[type=checkbox]' + assert_select "label[for=user_active_true][data-value=true]", "true" do + assert_select "input#user_active_true[type=checkbox]" end - assert_select 'label[for=user_active_false][data-value=false]', 'false' do - assert_select 'input#user_active_false[type=checkbox]' + assert_select "label[for=user_active_false][data-value=false]", "false" do + assert_select "input#user_active_false[type=checkbox]" end end - test 'collection check boxes with block helpers allows access to the current object item in the collection to access extra properties' do + test "collection check boxes with block helpers allows access to the current object item in the collection to access extra properties" do with_collection_check_boxes :user, :active, [true, false], :to_s, :to_s do |b| - b.label(:class => b.object) { b.check_box + b.text } + b.label(class: b.object) { b.check_box + b.text } end - assert_select 'label.true[for=user_active_true]', 'true' do - assert_select 'input#user_active_true[type=checkbox]' + assert_select "label.true[for=user_active_true]", "true" do + assert_select "input#user_active_true[type=checkbox]" end - assert_select 'label.false[for=user_active_false]', 'false' do - assert_select 'input#user_active_false[type=checkbox]' + assert_select "label.false[for=user_active_false]", "false" do + assert_select "input#user_active_false[type=checkbox]" end end end diff --git a/actionview/test/template/form_helper/form_with_test.rb b/actionview/test/template/form_helper/form_with_test.rb new file mode 100644 index 0000000000..0295ff627d --- /dev/null +++ b/actionview/test/template/form_helper/form_with_test.rb @@ -0,0 +1,2276 @@ +# frozen_string_literal: true + +require "abstract_unit" +require "controller/fake_models" + +class FormWithTest < ActionView::TestCase + include RenderERBUtils + + setup do + @old_value = ActionView::Helpers::FormHelper.form_with_generates_ids + ActionView::Helpers::FormHelper.form_with_generates_ids = true + end + + teardown do + ActionView::Helpers::FormHelper.form_with_generates_ids = @old_value + end +end + +class FormWithActsLikeFormTagTest < FormWithTest + tests ActionView::Helpers::FormTagHelper + + setup do + @controller = BasicController.new + end + + def hidden_fields(options = {}) + method = options[:method] + skip_enforcing_utf8 = options.fetch(:skip_enforcing_utf8, false) + + "".dup.tap do |txt| + unless skip_enforcing_utf8 + txt << %{<input name="utf8" type="hidden" value="✓" />} + end + + if method && !%w(get post).include?(method.to_s) + txt << %{<input name="_method" type="hidden" value="#{method}" />} + end + end + end + + def form_text(action = "http://www.example.com", local: false, **options) + enctype, html_class, id, method = options.values_at(:enctype, :html_class, :id, :method) + + method = method.to_s == "get" ? "get" : "post" + + txt = %{<form accept-charset="UTF-8" action="#{action}"}.dup + txt << %{ enctype="multipart/form-data"} if enctype + txt << %{ data-remote="true"} unless local + txt << %{ class="#{html_class}"} if html_class + txt << %{ id="#{id}"} if id + txt << %{ method="#{method}">} + end + + def whole_form(action = "http://www.example.com", options = {}) + out = form_text(action, options) + hidden_fields(options) + + if block_given? + out << yield << "</form>" + end + + out + end + + def url_for(options) + if options.is_a?(Hash) + "http://www.example.com" + else + super + end + end + + def test_form_with_multipart + actual = form_with(multipart: true) + + expected = whole_form("http://www.example.com", enctype: true) + assert_dom_equal expected, actual + end + + def test_form_with_with_method_patch + actual = form_with(method: :patch) + + expected = whole_form("http://www.example.com", method: :patch) + assert_dom_equal expected, actual + end + + def test_form_with_with_method_put + actual = form_with(method: :put) + + expected = whole_form("http://www.example.com", method: :put) + assert_dom_equal expected, actual + end + + def test_form_with_with_method_delete + actual = form_with(method: :delete) + + expected = whole_form("http://www.example.com", method: :delete) + assert_dom_equal expected, actual + end + + def test_form_with_with_local_true + actual = form_with(local: true) + + expected = whole_form("http://www.example.com", local: true) + assert_dom_equal expected, actual + end + + def test_form_with_skip_enforcing_utf8_true + actual = form_with(skip_enforcing_utf8: true) + expected = whole_form("http://www.example.com", skip_enforcing_utf8: true) + assert_dom_equal expected, actual + assert actual.html_safe? + end + + def test_form_with_with_block_in_erb + output_buffer = render_erb("<%= form_with(url: 'http://www.example.com') do %>Hello world!<% end %>") + + expected = whole_form { "Hello world!" } + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_block_and_method_in_erb + output_buffer = render_erb("<%= form_with(url: 'http://www.example.com', method: :put) do %>Hello world!<% end %>") + + expected = whole_form("http://www.example.com", method: "put") do + "Hello world!" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_block_in_erb_and_local_true + output_buffer = render_erb("<%= form_with(url: 'http://www.example.com', local: true) do %>Hello world!<% end %>") + + expected = whole_form("http://www.example.com", local: true) do + "Hello world!" + end + + assert_dom_equal expected, output_buffer + end +end + +class FormWithActsLikeFormForTest < FormWithTest + def form_with(*) + @output_buffer = super + end + + teardown do + I18n.backend.reload! + end + + setup do + # Create "label" locale for testing I18n label helpers + I18n.backend.store_translations "label", + activemodel: { + attributes: { + post: { + cost: "Total cost" + }, + "post/language": { + spanish: "Espanol" + } + } + }, + helpers: { + label: { + post: { + body: "Write entire text here", + color: { + red: "Rojo" + }, + comments: { + body: "Write body here" + } + }, + tag: { + value: "Tag" + }, + post_delegate: { + title: "Delegate model_name title" + } + } + } + + # Create "submit" locale for testing I18n submit helpers + I18n.backend.store_translations "submit", + helpers: { + submit: { + create: "Create %{model}", + update: "Confirm %{model} changes", + submit: "Save changes", + another_post: { + update: "Update your %{model}" + } + } + } + + I18n.backend.store_translations "placeholder", + activemodel: { + attributes: { + post: { + cost: "Total cost" + }, + "post/cost": { + uk: "Pounds" + } + } + }, + helpers: { + placeholder: { + post: { + title: "What is this about?", + written_on: { + spanish: "Escrito en" + }, + comments: { + body: "Write body here" + } + }, + post_delegate: { + title: "Delegate model_name title" + }, + tag: { + value: "Tag" + } + } + } + + @post = Post.new + @comment = Comment.new + def @post.errors + Class.new { + def [](field); field == "author_name" ? ["can't be empty"] : [] end + def empty?() false end + def count() 1 end + def full_messages() ["Author name can't be empty"] end + }.new + end + def @post.to_key; [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 + @post.title = "Hello World" + @post.author_name = "" + @post.body = "Back to the hill and over it again!" + @post.secret = 1 + @post.written_on = Date.new(2004, 6, 15) + + @post.comments = [] + @post.comments << @comment + + @post.tags = [] + @post.tags << Tag.new + + @post_delegator = PostDelegator.new + + @post_delegator.title = "Hello World" + + @car = Car.new("#000FFF") + end + + Routes = ActionDispatch::Routing::RouteSet.new + Routes.draw do + resources :posts do + resources :comments + end + + namespace :admin do + resources :posts do + resources :comments + end + end + + get "/foo", to: "controller#action" + root to: "main#index" + end + + def _routes + Routes + end + + include Routes.url_helpers + + def url_for(object) + @url_for_options = object + + if object.is_a?(Hash) && object[:use_route].blank? && object[:controller].blank? + object.merge!(controller: "main", action: "index") + end + + super + end + + def test_form_with_requires_arguments + error = assert_raises(ArgumentError) do + form_for(nil, html: { id: "create-post" }) do + end + end + assert_equal "First argument in form cannot contain nil or be empty", error.message + + error = assert_raises(ArgumentError) do + form_for([nil, nil], html: { id: "create-post" }) do + end + end + assert_equal "First argument in form cannot contain nil or be empty", error.message + end + + def test_form_with + form_with(model: @post, id: "create-post") do |f| + concat f.label(:title) { "The Title" } + concat f.text_field(:title) + concat f.text_area(:body) + concat f.check_box(:secret) + concat f.select(:category, %w( animal economy sports )) + concat f.submit("Create post") + concat f.button("Create post") + concat f.button { + concat content_tag(:span, "Create post") + } + end + + expected = whole_form("/posts/123", "create-post", method: "patch") do + "<label for='post_title'>The Title</label>" \ + "<input name='post[title]' type='text' value='Hello World' id='post_title' />" \ + "<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' value='1' id='post_secret' />" \ + "<select name='post[category]' id='post_category'><option value='animal'>animal</option>\n<option value='economy'>economy</option>\n<option value='sports'>sports</option></select>" \ + "<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 + + assert_dom_equal expected, output_buffer + end + + def test_form_with_not_outputting_ids + old_value = ActionView::Helpers::FormHelper.form_with_generates_ids + ActionView::Helpers::FormHelper.form_with_generates_ids = false + + form_with(model: @post, id: "create-post") do |f| + concat f.label(:title) { "The Title" } + concat f.text_field(:title) + concat f.text_area(:body) + concat f.check_box(:secret) + concat f.select(:category, %w( animal economy sports )) + concat f.submit("Create post") + end + + expected = whole_form("/posts/123", "create-post", method: "patch") do + "<label>The Title</label>" \ + "<input name='post[title]' type='text' value='Hello World' />" \ + "<textarea name='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' value='1' />" \ + "<select name='post[category]'><option value='animal'>animal</option>\n<option value='economy'>economy</option>\n<option value='sports'>sports</option></select>" \ + "<input name='commit' data-disable-with='Create post' type='submit' value='Create post' />" + end + + assert_dom_equal expected, output_buffer + ensure + ActionView::Helpers::FormHelper.form_with_generates_ids = old_value + end + + def test_form_with_only_url_on_create + form_with(url: "/posts") do |f| + concat f.label :title, "Label me" + concat f.text_field :title + end + + expected = whole_form("/posts") do + '<label for="title">Label me</label>' \ + '<input type="text" name="title" id="title">' + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_only_url_on_update + form_with(url: "/posts/123") do |f| + concat f.label :title, "Label me" + concat f.text_field :title + end + + expected = whole_form("/posts/123") do + '<label for="title">Label me</label>' \ + '<input type="text" name="title" id="title">' + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_general_attributes + form_with(url: "/posts/123") do |f| + concat f.text_field :no_model_to_back_this_badboy + end + + expected = whole_form("/posts/123") do + '<input type="text" name="no_model_to_back_this_badboy" id="no_model_to_back_this_badboy" >' + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_attribute_not_on_model + form_with(model: @post) do |f| + concat f.text_field :this_dont_exist_on_post + end + + expected = whole_form("/posts/123", method: :patch) do + '<input type="text" name="post[this_dont_exist_on_post]" id="post_this_dont_exist_on_post" >' + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_doesnt_call_private_or_protected_properties_on_form_object_skipping_value + obj = Class.new do + private def private_property + "That would be great." + end + + protected def protected_property + "I believe you have my stapler." + end + end.new + + form_with(model: obj, scope: "other_name", url: "/", id: "edit-other-name") do |f| + assert_dom_equal '<input type="hidden" name="other_name[private_property]" id="other_name_private_property">', f.hidden_field(:private_property) + assert_dom_equal '<input type="hidden" name="other_name[protected_property]" id="other_name_protected_property">', f.hidden_field(:protected_property) + end + end + + def test_form_with_with_collection_radio_buttons + post = Post.new + def post.active; false; end + form_with(model: post) do |f| + concat f.collection_radio_buttons(:active, [true, false], :to_s, :to_s) + end + + expected = whole_form("/posts") do + "<input type='hidden' name='post[active]' value='' />" \ + "<input name='post[active]' type='radio' value='true' id='post_active_true' />" \ + "<label for='post_active_true'>true</label>" \ + "<input checked='checked' name='post[active]' type='radio' value='false' id='post_active_false' />" \ + "<label for='post_active_false'>false</label>" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_collection_radio_buttons_with_custom_builder_block + post = Post.new + def post.active; false; end + + form_with(model: post) do |f| + rendered_radio_buttons = f.collection_radio_buttons(:active, [true, false], :to_s, :to_s) do |b| + b.label { b.radio_button + b.text } + end + concat rendered_radio_buttons + end + + expected = whole_form("/posts") do + "<input type='hidden' name='post[active]' value='' />" \ + "<label for='post_active_true'>" \ + "<input name='post[active]' type='radio' value='true' id='post_active_true' />" \ + "true</label>" \ + "<label for='post_active_false'>" \ + "<input checked='checked' name='post[active]' type='radio' value='false' id='post_active_false' />" \ + "false</label>" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_collection_radio_buttons_with_custom_builder_block_does_not_leak_the_template + post = Post.new + def post.active; false; end + def post.id; 1; end + + form_with(model: post) do |f| + rendered_radio_buttons = f.collection_radio_buttons(:active, [true, false], :to_s, :to_s) do |b| + b.label { b.radio_button + b.text } + end + concat rendered_radio_buttons + concat f.hidden_field :id + end + + expected = whole_form("/posts") do + "<input type='hidden' name='post[active]' value='' />" \ + "<label for='post_active_true'>" \ + "<input name='post[active]' type='radio' value='true' id='post_active_true' />" \ + "true</label>" \ + "<label for='post_active_false'>" \ + "<input checked='checked' name='post[active]' type='radio' value='false' id='post_active_false' />" \ + "false</label>" \ + "<input name='post[id]' type='hidden' value='1' id='post_id' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_index_and_with_collection_radio_buttons + post = Post.new + def post.active; false; end + + form_with(model: post, index: "1") do |f| + concat f.collection_radio_buttons(:active, [true, false], :to_s, :to_s) + end + + expected = whole_form("/posts") do + "<input type='hidden' name='post[1][active]' value='' />" \ + "<input name='post[1][active]' type='radio' value='true' id='post_1_active_true' />" \ + "<label for='post_1_active_true'>true</label>" \ + "<input checked='checked' name='post[1][active]' type='radio' value='false' id='post_1_active_false' />" \ + "<label for='post_1_active_false'>false</label>" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_collection_check_boxes + post = Post.new + def post.tag_ids; [1, 3]; end + collection = (1..3).map { |i| [i, "Tag #{i}"] } + form_with(model: post) do |f| + concat f.collection_check_boxes(:tag_ids, collection, :first, :last) + end + + expected = whole_form("/posts") do + "<input name='post[tag_ids][]' type='hidden' value='' />" \ + "<input checked='checked' name='post[tag_ids][]' type='checkbox' value='1' id='post_tag_ids_1' />" \ + "<label for='post_tag_ids_1'>Tag 1</label>" \ + "<input name='post[tag_ids][]' type='checkbox' value='2' id='post_tag_ids_2' />" \ + "<label for='post_tag_ids_2'>Tag 2</label>" \ + "<input checked='checked' name='post[tag_ids][]' type='checkbox' value='3' id='post_tag_ids_3' />" \ + "<label for='post_tag_ids_3'>Tag 3</label>" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_collection_check_boxes_with_custom_builder_block + post = Post.new + def post.tag_ids; [1, 3]; end + collection = (1..3).map { |i| [i, "Tag #{i}"] } + form_with(model: post) do |f| + rendered_check_boxes = f.collection_check_boxes(:tag_ids, collection, :first, :last) do |b| + b.label { b.check_box + b.text } + end + concat rendered_check_boxes + end + + expected = whole_form("/posts") do + "<input name='post[tag_ids][]' type='hidden' value='' />" \ + "<label for='post_tag_ids_1'>" \ + "<input checked='checked' name='post[tag_ids][]' type='checkbox' value='1' id='post_tag_ids_1' />" \ + "Tag 1</label>" \ + "<label for='post_tag_ids_2'>" \ + "<input name='post[tag_ids][]' type='checkbox' value='2' id='post_tag_ids_2' />" \ + "Tag 2</label>" \ + "<label for='post_tag_ids_3'>" \ + "<input checked='checked' name='post[tag_ids][]' type='checkbox' value='3' id='post_tag_ids_3' />" \ + "Tag 3</label>" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_collection_check_boxes_with_custom_builder_block_does_not_leak_the_template + post = Post.new + def post.tag_ids; [1, 3]; end + def post.id; 1; end + collection = (1..3).map { |i| [i, "Tag #{i}"] } + + form_with(model: post) do |f| + rendered_check_boxes = f.collection_check_boxes(:tag_ids, collection, :first, :last) do |b| + b.label { b.check_box + b.text } + end + concat rendered_check_boxes + concat f.hidden_field :id + end + + expected = whole_form("/posts") do + "<input name='post[tag_ids][]' type='hidden' value='' />" \ + "<label for='post_tag_ids_1'>" \ + "<input checked='checked' name='post[tag_ids][]' type='checkbox' value='1' id='post_tag_ids_1' />" \ + "Tag 1</label>" \ + "<label for='post_tag_ids_2'>" \ + "<input name='post[tag_ids][]' type='checkbox' value='2' id='post_tag_ids_2' />" \ + "Tag 2</label>" \ + "<label for='post_tag_ids_3'>" \ + "<input checked='checked' name='post[tag_ids][]' type='checkbox' value='3' id='post_tag_ids_3' />" \ + "Tag 3</label>" \ + "<input name='post[id]' type='hidden' value='1' id='post_id' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_index_and_with_collection_check_boxes + post = Post.new + def post.tag_ids; [1]; end + collection = [[1, "Tag 1"]] + + form_with(model: post, index: "1") do |f| + concat f.collection_check_boxes(:tag_ids, collection, :first, :last) + end + + expected = whole_form("/posts") do + "<input name='post[1][tag_ids][]' type='hidden' value='' />" \ + "<input checked='checked' name='post[1][tag_ids][]' type='checkbox' value='1' id='post_1_tag_ids_1' />" \ + "<label for='post_1_tag_ids_1'>Tag 1</label>" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_file_field_generate_multipart + form_with(model: @post, id: "create-post") do |f| + concat f.file_field(:file) + end + + expected = whole_form("/posts/123", "create-post", method: "patch", multipart: true) do + "<input name='post[file]' type='file' id='post_file' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_fields_with_file_field_generate_multipart + form_with(model: @post) do |f| + concat f.fields(:comment, model: @post) { |c| + concat c.file_field(:file) + } + end + + expected = whole_form("/posts/123", method: "patch", multipart: true) do + "<input name='post[comment][file]' type='file' id='post_comment_file'/>" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_format + form_with(model: @post, format: :json, id: "edit_post_123", class: "edit_post") do |f| + concat f.label(:title) + end + + expected = whole_form("/posts/123.json", "edit_post_123", "edit_post", method: "patch") do + "<label for='post_title'>Title</label>" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_format_and_url + form_with(model: @post, format: :json, url: "/") do |f| + concat f.label(:title) + end + + expected = whole_form("/", method: "patch") do + "<label for='post_title'>Title</label>" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_model_using_relative_model_naming + blog_post = Blog::Post.new("And his name will be forty and four.", 44) + + form_with(model: blog_post) do |f| + concat f.text_field :title + concat f.submit("Edit post") + end + + expected = whole_form("/posts/44", method: "patch") do + "<input name='post[title]' type='text' value='And his name will be forty and four.' id='post_title' />" \ + "<input name='commit' data-disable-with='Edit post' type='submit' value='Edit post' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_symbol_scope + form_with(model: @post, scope: "other_name", id: "create-post") do |f| + concat f.label(:title, class: "post_title") + concat f.text_field(:title) + concat f.text_area(:body) + concat f.check_box(:secret) + concat f.submit("Create post") + end + + expected = whole_form("/posts/123", "create-post", method: "patch") do + "<label for='other_name_title' class='post_title'>Title</label>" \ + "<input name='other_name[title]' value='Hello World' type='text' id='other_name_title' />" \ + "<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' value='1' type='checkbox' id='other_name_secret' />" \ + "<input name='commit' value='Create post' data-disable-with='Create post' type='submit' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_method_as_part_of_html_options + form_with(model: @post, url: "/", id: "create-post", html: { method: :delete }) do |f| + concat f.text_field(:title) + concat f.text_area(:body) + concat f.check_box(:secret) + end + + expected = whole_form("/", "create-post", method: "delete") do + "<input name='post[title]' type='text' value='Hello World' id='post_title' />" \ + "<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' value='1' id='post_secret'/>" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_method + form_with(model: @post, url: "/", method: :delete, id: "create-post") do |f| + concat f.text_field(:title) + concat f.text_area(:body) + concat f.check_box(:secret) + end + + expected = whole_form("/", "create-post", method: "delete") do + "<input name='post[title]' type='text' value='Hello World' id='post_title' />" \ + "<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' value='1' id='post_secret' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_search_field + # Test case for bug which would emit an "object" attribute + # when used with form_for using a search_field form helper + form_with(model: Post.new, url: "/search", id: "search-post", method: :get) do |f| + concat f.search_field(:title) + end + + expected = whole_form("/search", "search-post", method: "get") do + "<input name='post[title]' type='search' id='post_title' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_enables_remote_by_default + form_with(model: @post, url: "/", id: "create-post", method: :patch) do |f| + concat f.text_field(:title) + concat f.text_area(:body) + concat f.check_box(:secret) + end + + expected = whole_form("/", "create-post", method: "patch") do + "<input name='post[title]' type='text' value='Hello World' id='post_title' />" \ + "<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' value='1' id='post_secret' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_is_not_remote_by_default_if_form_with_generates_remote_forms_is_false + old_value = ActionView::Helpers::FormHelper.form_with_generates_remote_forms + ActionView::Helpers::FormHelper.form_with_generates_remote_forms = false + + form_with(model: @post, url: "/", id: "create-post", method: :patch) do |f| + concat f.text_field(:title) + concat f.text_area(:body) + concat f.check_box(:secret) + end + + expected = whole_form("/", "create-post", method: "patch", local: true) do + "<input name='post[title]' type='text' value='Hello World' id='post_title' />" \ + "<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' value='1' id='post_secret' />" + end + + assert_dom_equal expected, output_buffer + ensure + ActionView::Helpers::FormHelper.form_with_generates_remote_forms = old_value + end + + def test_form_with_skip_enforcing_utf8_true + form_with(scope: :post, skip_enforcing_utf8: true) do |f| + concat f.text_field(:title) + end + + expected = whole_form("/", skip_enforcing_utf8: true) do + "<input name='post[title]' type='text' value='Hello World' id='post_title' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_skip_enforcing_utf8_false + form_with(scope: :post, skip_enforcing_utf8: false) do |f| + concat f.text_field(:title) + end + + expected = whole_form("/", skip_enforcing_utf8: false) do + "<input name='post[title]' type='text' value='Hello World' id='post_title' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_without_object + form_with(scope: :post, id: "create-post") do |f| + concat f.text_field(:title) + concat f.text_area(:body) + concat f.check_box(:secret) + end + + expected = whole_form("/", "create-post") do + "<input name='post[title]' type='text' value='Hello World' id='post_title' />" \ + "<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' value='1' id='post_secret' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_index + form_with(model: @post, scope: "post[]") do |f| + concat f.label(:title) + concat f.text_field(:title) + concat f.text_area(:body) + concat f.check_box(:secret) + end + + expected = whole_form("/posts/123", method: "patch") do + "<label for='post_123_title'>Title</label>" \ + "<input name='post[123][title]' type='text' value='Hello World' id='post_123_title' />" \ + "<textarea name='post[123][body]' id='post_123_body'>\nBack to the hill and over it again!</textarea>" \ + "<input name='post[123][secret]' type='hidden' value='0' />" \ + "<input name='post[123][secret]' checked='checked' type='checkbox' value='1' id='post_123_secret' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_nil_index_option_override + form_with(model: @post, scope: "post[]", index: nil) do |f| + concat f.text_field(:title) + concat f.text_area(:body) + concat f.check_box(:secret) + end + + expected = whole_form("/posts/123", method: "patch") do + "<input name='post[][title]' type='text' value='Hello World' id='post__title' />" \ + "<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' value='1' id='post__secret' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_label_error_wrapping + form_with(model: @post) do |f| + concat f.label(:author_name, class: "label") + concat f.text_field(:author_name) + concat f.submit("Create post") + end + + expected = whole_form("/posts/123", 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' value='' id='post_author_name' /></div>" \ + "<input name='commit' data-disable-with='Create post' type='submit' value='Create post' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_label_error_wrapping_without_conventional_instance_variable + post = remove_instance_variable :@post + + form_with(model: post) do |f| + concat f.label(:author_name, class: "label") + concat f.text_field(:author_name) + concat f.submit("Create post") + end + + expected = whole_form("/posts/123", 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' value='' id='post_author_name' /></div>" \ + "<input name='commit' data-disable-with='Create post' type='submit' value='Create post' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_label_error_wrapping_block_and_non_block_versions + form_with(model: @post) do |f| + concat f.label(:author_name, "Name", class: "label") + concat f.label(:author_name, class: "label") { "Name" } + end + + expected = whole_form("/posts/123", method: "patch") do + "<div class='field_with_errors'><label for='post_author_name' class='label'>Name</label></div>" \ + "<div class='field_with_errors'><label for='post_author_name' class='label'>Name</label></div>" + end + + assert_dom_equal expected, output_buffer + end + + def test_submit_with_object_as_new_record_and_locale_strings + with_locale :submit do + @post.persisted = false + @post.stub(:to_key, nil) do + form_with(model: @post) do |f| + concat f.submit + end + + expected = whole_form("/posts") do + "<input name='commit' data-disable-with='Create Post' type='submit' value='Create Post' />" + end + + assert_dom_equal expected, output_buffer + end + end + end + + def test_submit_with_object_as_existing_record_and_locale_strings + with_locale :submit do + form_with(model: @post) do |f| + concat f.submit + end + + expected = whole_form("/posts/123", method: "patch") do + "<input name='commit' data-disable-with='Confirm Post changes' type='submit' value='Confirm Post changes' />" + end + + assert_dom_equal expected, output_buffer + end + end + + def test_submit_without_object_and_locale_strings + with_locale :submit do + form_with(scope: :post) do |f| + concat f.submit class: "extra" + end + + expected = whole_form do + "<input name='commit' class='extra' data-disable-with='Save changes' type='submit' value='Save changes' />" + end + + assert_dom_equal expected, output_buffer + end + end + + def test_submit_with_object_and_nested_lookup + with_locale :submit do + form_with(model: @post, scope: :another_post) do |f| + concat f.submit + end + + expected = whole_form("/posts/123", method: "patch") do + "<input name='commit' data-disable-with='Update your Post' type='submit' value='Update your Post' />" + end + + assert_dom_equal expected, output_buffer + end + end + + def test_fields_with_attributes_not_on_model + form_with(model: @post) do |f| + concat f.fields(:comment) { |c| + concat c.text_field :dont_exist_on_model + } + end + + expected = whole_form("/posts/123", method: :patch) do + '<input type="text" name="post[comment][dont_exist_on_model]" id="post_comment_dont_exist_on_model" >' + end + + assert_dom_equal expected, output_buffer + end + + def test_fields_with_attributes_not_on_model_deep_nested + @comment.save + form_with(scope: :posts) do |f| + f.fields("post[]", model: @post) do |f2| + f2.text_field(:id) + @post.comments.each do |comment| + concat f2.fields("comment[]", model: comment) { |c| + concat c.text_field(:dont_exist_on_model) + } + end + end + end + + expected = whole_form do + '<input name="posts[post][0][comment][1][dont_exist_on_model]" type="text" id="posts_post_0_comment_1_dont_exist_on_model" >' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields + @comment.body = "Hello World" + form_with(model: @post) do |f| + concat f.fields(model: @comment) { |c| + concat c.text_field(:body) + } + end + + expected = whole_form("/posts/123", method: "patch") do + "<input name='post[comment][body]' type='text' value='Hello World' id='post_comment_body' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_deep_nested_fields + @comment.save + form_with(scope: :posts) do |f| + f.fields("post[]", model: @post) do |f2| + f2.text_field(:id) + @post.comments.each do |comment| + concat f2.fields("comment[]", model: comment) { |c| + concat c.text_field(:name) + } + end + end + end + + expected = whole_form do + "<input name='posts[post][0][comment][1][name]' type='text' value='comment #1' id='posts_post_0_comment_1_name' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_nested_collections + form_with(model: @post, scope: "post[]") do |f| + concat f.text_field(:title) + concat f.fields("comment[]", model: @comment) { |c| + concat c.text_field(:name) + } + end + + expected = whole_form("/posts/123", method: "patch") do + "<input name='post[123][title]' type='text' value='Hello World' id='post_123_title' />" \ + "<input name='post[123][comment][][name]' type='text' value='new comment' id='post_123_comment__name' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_index_and_parent_fields + form_with(model: @post, index: 1) do |c| + concat c.text_field(:title) + concat c.fields("comment", model: @comment, index: 1) { |r| + concat r.text_field(:name) + } + end + + expected = whole_form("/posts/123", method: "patch") do + "<input name='post[1][title]' type='text' value='Hello World' id='post_1_title' />" \ + "<input name='post[1][comment][1][name]' type='text' value='new comment' id='post_1_comment_1_name' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_index_and_nested_fields + output_buffer = form_with(model: @post, index: 1) do |f| + concat f.fields(:comment, model: @post) { |c| + concat c.text_field(:title) + } + end + + expected = whole_form("/posts/123", method: "patch") do + "<input name='post[1][comment][title]' type='text' value='Hello World' id='post_1_comment_title' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_index_on_both + form_with(model: @post, index: 1) do |f| + concat f.fields(:comment, model: @post, index: 5) { |c| + concat c.text_field(:title) + } + end + + expected = whole_form("/posts/123", method: "patch") do + "<input name='post[1][comment][5][title]' type='text' value='Hello World' id='post_1_comment_5_title' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_auto_index + form_with(model: @post, scope: "post[]") do |f| + concat f.fields(:comment, model: @post) { |c| + concat c.text_field(:title) + } + end + + expected = whole_form("/posts/123", method: "patch") do + "<input name='post[123][comment][title]' type='text' value='Hello World' id='post_123_comment_title' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_index_radio_button + form_with(model: @post) do |f| + concat f.fields(:comment, model: @post, index: 5) { |c| + concat c.radio_button(:title, "hello") + } + end + + expected = whole_form("/posts/123", method: "patch") do + "<input name='post[comment][5][title]' type='radio' value='hello' id='post_comment_5_title_hello' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_auto_index_on_both + form_with(model: @post, scope: "post[]") do |f| + concat f.fields("comment[]", model: @post) { |c| + concat c.text_field(:title) + } + end + + expected = whole_form("/posts/123", method: "patch") do + "<input name='post[123][comment][123][title]' type='text' value='Hello World' id='post_123_comment_123_title' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_index_and_auto_index + output_buffer = form_with(model: @post, scope: "post[]") do |f| + concat f.fields(:comment, model: @post, index: 5) { |c| + concat c.text_field(:title) + } + end + + output_buffer << form_with(model: @post, index: 1) do |f| + concat f.fields("comment[]", model: @post) { |c| + concat c.text_field(:title) + } + end + + expected = whole_form("/posts/123", method: "patch") do + "<input name='post[123][comment][5][title]' type='text' value='Hello World' id='post_123_comment_5_title' />" + end + whole_form("/posts/123", method: "patch") do + "<input name='post[1][comment][123][title]' type='text' value='Hello World' id='post_1_comment_123_title' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_a_new_record_on_a_nested_attributes_one_to_one_association + @post.author = Author.new + + form_with(model: @post) do |f| + concat f.text_field(:title) + concat f.fields(:author) { |af| + concat af.text_field(:name) + } + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[title]" type="text" value="Hello World" id="post_title" />' \ + '<input name="post[author_attributes][name]" type="text" value="new author" id="post_author_attributes_name" />' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_explicitly_passed_object_on_a_nested_attributes_one_to_one_association + form_with(model: @post) do |f| + f.fields(:author, model: Author.new(123)) do |af| + assert_not_nil af.object + assert_equal 123, af.object.id + end + end + end + + def test_nested_fields_with_an_existing_record_on_a_nested_attributes_one_to_one_association + @post.author = Author.new(321) + + form_with(model: @post) do |f| + concat f.text_field(:title) + concat f.fields(:author) { |af| + concat af.text_field(:name) + } + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[title]" type="text" value="Hello World" id="post_title" />' \ + '<input name="post[author_attributes][name]" type="text" value="author #321" id="post_author_attributes_name" />' \ + '<input name="post[author_attributes][id]" type="hidden" value="321" id="post_author_attributes_id" />' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_an_existing_record_on_a_nested_attributes_one_to_one_association_using_erb_and_inline_block + @post.author = Author.new(321) + + form_with(model: @post) do |f| + concat f.text_field(:title) + concat f.fields(:author) { |af| + af.text_field(:name) + } + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[title]" type="text" value="Hello World" id="post_title" />' \ + '<input name="post[author_attributes][name]" type="text" value="author #321" id="post_author_attributes_name" />' \ + '<input name="post[author_attributes][id]" type="hidden" value="321" id="post_author_attributes_id" />' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_an_existing_record_on_a_nested_attributes_one_to_one_association_with_disabled_hidden_id + @post.author = Author.new(321) + + form_with(model: @post) do |f| + concat f.text_field(:title) + concat f.fields(:author, skip_id: true) { |af| + af.text_field(:name) + } + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[title]" type="text" value="Hello World" id="post_title" />' \ + '<input name="post[author_attributes][name]" type="text" value="author #321" id="post_author_attributes_name" />' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_an_existing_record_on_a_nested_attributes_one_to_one_association_with_disabled_hidden_id_inherited + @post.author = Author.new(321) + + form_with(model: @post, skip_id: true) do |f| + concat f.text_field(:title) + concat f.fields(:author) { |af| + af.text_field(:name) + } + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[title]" type="text" value="Hello World" id="post_title" />' \ + '<input name="post[author_attributes][name]" type="text" value="author #321" id="post_author_attributes_name" />' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_an_existing_record_on_a_nested_attributes_one_to_one_association_with_disabled_hidden_id_override + @post.author = Author.new(321) + + form_with(model: @post, skip_id: true) do |f| + concat f.text_field(:title) + concat f.fields(:author, skip_id: false) { |af| + af.text_field(:name) + } + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[title]" type="text" value="Hello World" id="post_title" />' \ + '<input name="post[author_attributes][name]" type="text" value="author #321" id="post_author_attributes_name" />' \ + '<input name="post[author_attributes][id]" type="hidden" value="321" id="post_author_attributes_id" />' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_existing_records_on_a_nested_attributes_one_to_one_association_with_explicit_hidden_field_placement + @post.author = Author.new(321) + + form_with(model: @post) do |f| + concat f.text_field(:title) + concat f.fields(:author) { |af| + concat af.hidden_field(:id) + concat af.text_field(:name) + } + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[title]" type="text" value="Hello World" id="post_title" />' \ + '<input name="post[author_attributes][id]" type="hidden" value="321" id="post_author_attributes_id" />' \ + '<input name="post[author_attributes][name]" type="text" value="author #321" id="post_author_attributes_name" />' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_existing_records_on_a_nested_attributes_collection_association + @post.comments = Array.new(2) { |id| Comment.new(id + 1) } + + form_with(model: @post) do |f| + concat f.text_field(:title) + @post.comments.each do |comment| + concat f.fields(:comments, model: comment) { |cf| + concat cf.text_field(:name) + } + end + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[title]" type="text" value="Hello World" id="post_title" />' \ + '<input name="post[comments_attributes][0][name]" type="text" value="comment #1" id="post_comments_attributes_0_name" />' \ + '<input name="post[comments_attributes][0][id]" type="hidden" value="1" id="post_comments_attributes_0_id" />' \ + '<input name="post[comments_attributes][1][name]" type="text" value="comment #2" id="post_comments_attributes_1_name" />' \ + '<input name="post[comments_attributes][1][id]" type="hidden" value="2" id="post_comments_attributes_1_id" />' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_existing_records_on_a_nested_attributes_collection_association_with_disabled_hidden_id + @post.comments = Array.new(2) { |id| Comment.new(id + 1) } + @post.author = Author.new(321) + + form_with(model: @post) do |f| + concat f.text_field(:title) + concat f.fields(:author) { |af| + concat af.text_field(:name) + } + @post.comments.each do |comment| + concat f.fields(:comments, model: comment, skip_id: true) { |cf| + concat cf.text_field(:name) + } + end + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[title]" type="text" value="Hello World" id="post_title" />' \ + '<input name="post[author_attributes][name]" type="text" value="author #321" id="post_author_attributes_name" />' \ + '<input name="post[author_attributes][id]" type="hidden" value="321" id="post_author_attributes_id" />' \ + '<input name="post[comments_attributes][0][name]" type="text" value="comment #1" id="post_comments_attributes_0_name" />' \ + '<input name="post[comments_attributes][1][name]" type="text" value="comment #2" id="post_comments_attributes_1_name" />' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_existing_records_on_a_nested_attributes_collection_association_with_disabled_hidden_id_inherited + @post.comments = Array.new(2) { |id| Comment.new(id + 1) } + @post.author = Author.new(321) + + form_with(model: @post, skip_id: true) do |f| + concat f.text_field(:title) + concat f.fields(:author) { |af| + concat af.text_field(:name) + } + @post.comments.each do |comment| + concat f.fields(:comments, model: comment) { |cf| + concat cf.text_field(:name) + } + end + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[title]" type="text" value="Hello World" id="post_title" />' \ + '<input name="post[author_attributes][name]" type="text" value="author #321" id="post_author_attributes_name" />' \ + '<input name="post[comments_attributes][0][name]" type="text" value="comment #1" id="post_comments_attributes_0_name" />' \ + '<input name="post[comments_attributes][1][name]" type="text" value="comment #2" id="post_comments_attributes_1_name" />' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_existing_records_on_a_nested_attributes_collection_association_with_disabled_hidden_id_override + @post.comments = Array.new(2) { |id| Comment.new(id + 1) } + @post.author = Author.new(321) + + form_with(model: @post, skip_id: true) do |f| + concat f.text_field(:title) + concat f.fields(:author, skip_id: false) { |af| + concat af.text_field(:name) + } + @post.comments.each do |comment| + concat f.fields(:comments, model: comment) { |cf| + concat cf.text_field(:name) + } + end + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[title]" type="text" value="Hello World" id="post_title" />' \ + '<input name="post[author_attributes][name]" type="text" value="author #321" id="post_author_attributes_name" />' \ + '<input name="post[author_attributes][id]" type="hidden" value="321" id="post_author_attributes_id" />' \ + '<input name="post[comments_attributes][0][name]" type="text" value="comment #1" id="post_comments_attributes_0_name" />' \ + '<input name="post[comments_attributes][1][name]" type="text" value="comment #2" id="post_comments_attributes_1_name" />' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_existing_records_on_a_nested_attributes_collection_association_using_erb_and_inline_block + @post.comments = Array.new(2) { |id| Comment.new(id + 1) } + + form_with(model: @post) do |f| + concat f.text_field(:title) + @post.comments.each do |comment| + concat f.fields(:comments, model: comment) { |cf| + cf.text_field(:name) + } + end + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[title]" type="text" value="Hello World" id="post_title" />' \ + '<input name="post[comments_attributes][0][name]" type="text" value="comment #1" id="post_comments_attributes_0_name" />' \ + '<input name="post[comments_attributes][0][id]" type="hidden" value="1" id="post_comments_attributes_0_id" />' \ + '<input name="post[comments_attributes][1][name]" type="text" value="comment #2" id="post_comments_attributes_1_name" />' \ + '<input name="post[comments_attributes][1][id]" type="hidden" value="2" id="post_comments_attributes_1_id" />' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_existing_records_on_a_nested_attributes_collection_association_with_explicit_hidden_field_placement + @post.comments = Array.new(2) { |id| Comment.new(id + 1) } + + form_with(model: @post) do |f| + concat f.text_field(:title) + @post.comments.each do |comment| + concat f.fields(:comments, model: comment) { |cf| + concat cf.hidden_field(:id) + concat cf.text_field(:name) + } + end + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[title]" type="text" value="Hello World" id="post_title" />' \ + '<input name="post[comments_attributes][0][id]" type="hidden" value="1" id="post_comments_attributes_0_id" />' \ + '<input name="post[comments_attributes][0][name]" type="text" value="comment #1" id="post_comments_attributes_0_name" />' \ + '<input name="post[comments_attributes][1][id]" type="hidden" value="2" id="post_comments_attributes_1_id" />' \ + '<input name="post[comments_attributes][1][name]" type="text" value="comment #2" id="post_comments_attributes_1_name" />' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_new_records_on_a_nested_attributes_collection_association + @post.comments = [Comment.new, Comment.new] + + form_with(model: @post) do |f| + concat f.text_field(:title) + @post.comments.each do |comment| + concat f.fields(:comments, model: comment) { |cf| + concat cf.text_field(:name) + } + end + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[title]" type="text" value="Hello World" id="post_title" />' \ + '<input name="post[comments_attributes][0][name]" type="text" value="new comment" id="post_comments_attributes_0_name" />' \ + '<input name="post[comments_attributes][1][name]" type="text" value="new comment" id="post_comments_attributes_1_name" />' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_existing_and_new_records_on_a_nested_attributes_collection_association + @post.comments = [Comment.new(321), Comment.new] + + form_with(model: @post) do |f| + concat f.text_field(:title) + @post.comments.each do |comment| + concat f.fields(:comments, model: comment) { |cf| + concat cf.text_field(:name) + } + end + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[title]" type="text" value="Hello World" id="post_title" />' \ + '<input name="post[comments_attributes][0][name]" type="text" value="comment #321" id="post_comments_attributes_0_name" />' \ + '<input name="post[comments_attributes][0][id]" type="hidden" value="321" id="post_comments_attributes_0_id"/>' \ + '<input name="post[comments_attributes][1][name]" type="text" value="new comment" id="post_comments_attributes_1_name" />' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_an_empty_supplied_attributes_collection + form_with(model: @post) do |f| + concat f.text_field(:title) + f.fields(:comments, model: []) do |cf| + concat cf.text_field(:name) + end + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[title]" type="text" value="Hello World" id="post_title" />' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_existing_records_on_a_supplied_nested_attributes_collection + @post.comments = Array.new(2) { |id| Comment.new(id + 1) } + + form_with(model: @post) do |f| + concat f.text_field(:title) + concat f.fields(:comments, model: @post.comments) { |cf| + concat cf.text_field(:name) + } + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[title]" type="text" value="Hello World" id="post_title" />' \ + '<input name="post[comments_attributes][0][name]" type="text" value="comment #1" id="post_comments_attributes_0_name" />' \ + '<input name="post[comments_attributes][0][id]" type="hidden" value="1" id="post_comments_attributes_0_id" />' \ + '<input name="post[comments_attributes][1][name]" type="text" value="comment #2" id="post_comments_attributes_1_name" />' \ + '<input name="post[comments_attributes][1][id]" type="hidden" value="2" id="post_comments_attributes_1_id" />' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_arel_like + @post.comments = ArelLike.new + + form_with(model: @post) do |f| + concat f.text_field(:title) + concat f.fields(:comments, model: @post.comments) { |cf| + concat cf.text_field(:name) + } + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[title]" type="text" value="Hello World" id="post_title" />' \ + '<input name="post[comments_attributes][0][name]" type="text" value="comment #1" id="post_comments_attributes_0_name" />' \ + '<input name="post[comments_attributes][0][id]" type="hidden" value="1" id="post_comments_attributes_0_id" />' \ + '<input name="post[comments_attributes][1][name]" type="text" value="comment #2" id="post_comments_attributes_1_name" />' \ + '<input name="post[comments_attributes][1][id]" type="hidden" value="2" id="post_comments_attributes_1_id" />' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_label_translation_with_more_than_10_records + @post.comments = Array.new(11) { |id| Comment.new(id + 1) } + + 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_with(model: @post) do |f| + f.fields(:comments) do |cf| + concat cf.label(:body) + end + end + end + end + + def test_nested_fields_with_existing_records_on_a_supplied_nested_attributes_collection_different_from_record_one + comments = Array.new(2) { |id| Comment.new(id + 1) } + @post.comments = [] + + form_with(model: @post) do |f| + concat f.text_field(:title) + concat f.fields(:comments, model: comments) { |cf| + concat cf.text_field(:name) + } + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[title]" type="text" value="Hello World" id="post_title" />' \ + '<input name="post[comments_attributes][0][name]" type="text" value="comment #1" id="post_comments_attributes_0_name" />' \ + '<input name="post[comments_attributes][0][id]" type="hidden" value="1" id="post_comments_attributes_0_id" />' \ + '<input name="post[comments_attributes][1][name]" type="text" value="comment #2" id="post_comments_attributes_1_name" />' \ + '<input name="post[comments_attributes][1][id]" type="hidden" value="2" id="post_comments_attributes_1_id" />' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_on_a_nested_attributes_collection_association_yields_only_builder + @post.comments = [Comment.new(321), Comment.new] + yielded_comments = [] + + form_with(model: @post) do |f| + concat f.text_field(:title) + concat f.fields(:comments) { |cf| + concat cf.text_field(:name) + yielded_comments << cf.object + } + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[title]" type="text" value="Hello World" id="post_title" />' \ + '<input name="post[comments_attributes][0][name]" type="text" value="comment #321" id="post_comments_attributes_0_name" />' \ + '<input name="post[comments_attributes][0][id]" type="hidden" value="321" id="post_comments_attributes_0_id" />' \ + '<input name="post[comments_attributes][1][name]" type="text" value="new comment" id="post_comments_attributes_1_name" />' + end + + assert_dom_equal expected, output_buffer + assert_equal yielded_comments, @post.comments + end + + def test_nested_fields_with_child_index_option_override_on_a_nested_attributes_collection_association + @post.comments = [] + + form_with(model: @post) do |f| + concat f.fields(:comments, model: Comment.new(321), child_index: "abc") { |cf| + concat cf.text_field(:name) + } + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[comments_attributes][abc][name]" type="text" value="comment #321" id="post_comments_attributes_abc_name" />' \ + '<input name="post[comments_attributes][abc][id]" type="hidden" value="321" id="post_comments_attributes_abc_id" />' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_child_index_as_lambda_option_override_on_a_nested_attributes_collection_association + @post.comments = [] + + form_with(model: @post) do |f| + concat f.fields(:comments, model: Comment.new(321), child_index: -> { "abc" }) { |cf| + concat cf.text_field(:name) + } + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[comments_attributes][abc][name]" type="text" value="comment #321" id="post_comments_attributes_abc_name" />' \ + '<input name="post[comments_attributes][abc][id]" type="hidden" value="321" id="post_comments_attributes_abc_id" />' + end + + assert_dom_equal expected, output_buffer + end + + class FakeAssociationProxy + def to_ary + [1, 2, 3] + end + end + + def test_nested_fields_with_child_index_option_override_on_a_nested_attributes_collection_association_with_proxy + @post.comments = FakeAssociationProxy.new + + form_with(model: @post) do |f| + concat f.fields(:comments, model: Comment.new(321), child_index: "abc") { |cf| + concat cf.text_field(:name) + } + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[comments_attributes][abc][name]" type="text" value="comment #321" id="post_comments_attributes_abc_name" />' \ + '<input name="post[comments_attributes][abc][id]" type="hidden" value="321" id="post_comments_attributes_abc_id" />' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_index_method_with_existing_records_on_a_nested_attributes_collection_association + @post.comments = Array.new(2) { |id| Comment.new(id + 1) } + + form_with(model: @post) do |f| + expected = 0 + @post.comments.each do |comment| + f.fields(:comments, model: comment) { |cf| + assert_equal expected, cf.index + expected += 1 + } + end + end + end + + def test_nested_fields_index_method_with_existing_and_new_records_on_a_nested_attributes_collection_association + @post.comments = [Comment.new(321), Comment.new] + + form_with(model: @post) do |f| + expected = 0 + @post.comments.each do |comment| + f.fields(:comments, model: comment) { |cf| + assert_equal expected, cf.index + expected += 1 + } + end + end + end + + def test_nested_fields_index_method_with_existing_records_on_a_supplied_nested_attributes_collection + @post.comments = Array.new(2) { |id| Comment.new(id + 1) } + + form_with(model: @post) do |f| + expected = 0 + f.fields(:comments, model: @post.comments) { |cf| + assert_equal expected, cf.index + expected += 1 + } + end + end + + def test_nested_fields_index_method_with_child_index_option_override_on_a_nested_attributes_collection_association + @post.comments = [] + + form_with(model: @post) do |f| + f.fields(:comments, model: Comment.new(321), child_index: "abc") { |cf| + assert_equal "abc", cf.index + } + end + end + + def test_nested_fields_uses_unique_indices_for_different_collection_associations + @post.comments = [Comment.new(321)] + @post.tags = [Tag.new(123), Tag.new(456)] + @post.comments[0].relevances = [] + @post.tags[0].relevances = [] + @post.tags[1].relevances = [] + + form_with(model: @post) do |f| + concat f.fields(:comments, model: @post.comments[0]) { |cf| + concat cf.text_field(:name) + concat cf.fields(:relevances, model: CommentRelevance.new(314)) { |crf| + concat crf.text_field(:value) + } + } + concat f.fields(:tags, model: @post.tags[0]) { |tf| + concat tf.text_field(:value) + concat tf.fields(:relevances, model: TagRelevance.new(3141)) { |trf| + concat trf.text_field(:value) + } + } + concat f.fields("tags", model: @post.tags[1]) { |tf| + concat tf.text_field(:value) + concat tf.fields(:relevances, model: TagRelevance.new(31415)) { |trf| + concat trf.text_field(:value) + } + } + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[comments_attributes][0][name]" type="text" value="comment #321" id="post_comments_attributes_0_name" />' \ + '<input name="post[comments_attributes][0][relevances_attributes][0][value]" type="text" value="commentrelevance #314" id="post_comments_attributes_0_relevances_attributes_0_value" />' \ + '<input name="post[comments_attributes][0][relevances_attributes][0][id]" type="hidden" value="314" id="post_comments_attributes_0_relevances_attributes_0_id"/>' \ + '<input name="post[comments_attributes][0][id]" type="hidden" value="321" id="post_comments_attributes_0_id"/>' \ + '<input name="post[tags_attributes][0][value]" type="text" value="tag #123" id="post_tags_attributes_0_value"/>' \ + '<input name="post[tags_attributes][0][relevances_attributes][0][value]" type="text" value="tagrelevance #3141" id="post_tags_attributes_0_relevances_attributes_0_value"/>' \ + '<input name="post[tags_attributes][0][relevances_attributes][0][id]" type="hidden" value="3141" id="post_tags_attributes_0_relevances_attributes_0_id"/>' \ + '<input name="post[tags_attributes][0][id]" type="hidden" value="123" id="post_tags_attributes_0_id"/>' \ + '<input name="post[tags_attributes][1][value]" type="text" value="tag #456" id="post_tags_attributes_1_value"/>' \ + '<input name="post[tags_attributes][1][relevances_attributes][0][value]" type="text" value="tagrelevance #31415" id="post_tags_attributes_1_relevances_attributes_0_value"/>' \ + '<input name="post[tags_attributes][1][relevances_attributes][0][id]" type="hidden" value="31415" id="post_tags_attributes_1_relevances_attributes_0_id"/>' \ + '<input name="post[tags_attributes][1][id]" type="hidden" value="456" id="post_tags_attributes_1_id"/>' + end + + assert_dom_equal expected, output_buffer + end + + def test_nested_fields_with_hash_like_model + @author = HashBackedAuthor.new + + form_with(model: @post) do |f| + concat f.fields(:author, model: @author) { |af| + concat af.text_field(:name) + } + end + + expected = whole_form("/posts/123", method: "patch") do + '<input name="post[author_attributes][name]" type="text" value="hash backed author" id="post_author_attributes_name" />' + end + + assert_dom_equal expected, output_buffer + end + + def test_fields + output_buffer = fields(:post, model: @post) do |f| + concat f.text_field(:title) + concat f.text_area(:body) + concat f.check_box(:secret) + end + + expected = + "<input name='post[title]' type='text' value='Hello World' id='post_title' />" \ + "<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' value='1' id='post_secret' />" + + assert_dom_equal expected, output_buffer + end + + def test_fields_with_index + output_buffer = fields("post[]", model: @post) do |f| + concat f.text_field(:title) + concat f.text_area(:body) + concat f.check_box(:secret) + end + + expected = + "<input name='post[123][title]' type='text' value='Hello World' id='post_123_title' />" \ + "<textarea name='post[123][body]' id='post_123_body'>\nBack to the hill and over it again!</textarea>" \ + "<input name='post[123][secret]' type='hidden' value='0' />" \ + "<input name='post[123][secret]' checked='checked' type='checkbox' value='1' id='post_123_secret' />" + + assert_dom_equal expected, output_buffer + end + + def test_fields_with_nil_index_option_override + output_buffer = fields("post[]", model: @post, index: nil) do |f| + concat f.text_field(:title) + concat f.text_area(:body) + concat f.check_box(:secret) + end + + expected = + "<input name='post[][title]' type='text' value='Hello World' id='post__title' />" \ + "<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' value='1' id='post__secret' />" + + assert_dom_equal expected, output_buffer + end + + def test_fields_with_index_option_override + output_buffer = fields("post[]", model: @post, index: "abc") do |f| + concat f.text_field(:title) + concat f.text_area(:body) + concat f.check_box(:secret) + end + + expected = + "<input name='post[abc][title]' type='text' value='Hello World' id='post_abc_title' />" \ + "<textarea name='post[abc][body]' id='post_abc_body'>\nBack to the hill and over it again!</textarea>" \ + "<input name='post[abc][secret]' type='hidden' value='0' />" \ + "<input name='post[abc][secret]' checked='checked' type='checkbox' value='1' id='post_abc_secret' />" + + assert_dom_equal expected, output_buffer + end + + def test_fields_without_object + output_buffer = fields(:post) do |f| + concat f.text_field(:title) + concat f.text_area(:body) + concat f.check_box(:secret) + end + + expected = + "<input name='post[title]' type='text' value='Hello World' id='post_title' />" \ + "<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' value='1' id='post_secret' />" + + assert_dom_equal expected, output_buffer + end + + def test_fields_with_only_object + output_buffer = fields(model: @post) do |f| + concat f.text_field(:title) + concat f.text_area(:body) + concat f.check_box(:secret) + end + + expected = + "<input name='post[title]' type='text' value='Hello World' id='post_title' />" \ + "<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' value='1' id='post_secret' />" + + assert_dom_equal expected, output_buffer + end + + def test_fields_object_with_bracketed_name + output_buffer = fields("author[post]", model: @post) do |f| + concat f.label(:title) + concat f.text_field(:title) + end + + assert_dom_equal "<label for=\"author_post_title\">Title</label>" \ + "<input name='author[post][title]' type='text' value='Hello World' id='author_post_title' id='author_post_1_title' />", + output_buffer + end + + def test_fields_object_with_bracketed_name_and_index + output_buffer = fields("author[post]", model: @post, index: 1) do |f| + concat f.label(:title) + concat f.text_field(:title) + end + + assert_dom_equal "<label for=\"author_post_1_title\">Title</label>" \ + "<input name='author[post][1][title]' type='text' value='Hello World' id='author_post_1_title' />", + output_buffer + end + + def test_form_builder_does_not_have_form_with_method + assert_not_includes ActionView::Helpers::FormBuilder.instance_methods, :form_with + end + + def test_form_with_and_fields + form_with(model: @post, scope: :post, id: "create-post") do |post_form| + concat post_form.text_field(:title) + concat post_form.text_area(:body) + + concat fields(:parent_post, model: @post) { |parent_fields| + concat parent_fields.check_box(:secret) + } + end + + expected = whole_form("/posts/123", "create-post", method: "patch") do + "<input name='post[title]' type='text' value='Hello World' id='post_title' />" \ + "<textarea name='post[body]' id='post_body' >\nBack to the hill and over it again!</textarea>" \ + "<input name='parent_post[secret]' type='hidden' value='0' />" \ + "<input name='parent_post[secret]' checked='checked' type='checkbox' value='1' id='parent_post_secret' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_and_fields_with_object + form_with(model: @post, scope: :post, id: "create-post") do |post_form| + concat post_form.text_field(:title) + concat post_form.text_area(:body) + + concat post_form.fields(model: @comment) { |comment_fields| + concat comment_fields.text_field(:name) + } + end + + expected = whole_form("/posts/123", "create-post", method: "patch") do + "<input name='post[title]' type='text' value='Hello World' id='post_title' />" \ + "<textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea>" \ + "<input name='post[comment][name]' type='text' value='new comment' id='post_comment_name' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_with_and_fields_with_non_nested_association_and_without_object + form_with(model: @post) do |f| + concat f.fields(:category) { |c| + concat c.text_field(:name) + } + end + + expected = whole_form("/posts/123", method: "patch") do + "<input name='post[category][name]' type='text' id='post_category_name' />" + end + + assert_dom_equal expected, output_buffer + end + + class LabelledFormBuilder < ActionView::Helpers::FormBuilder + (field_helpers - %w(hidden_field)).each do |selector| + class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1 + def #{selector}(field, *args, &proc) + ("<label for='\#{field}'>\#{field.to_s.humanize}:</label> " + super + "<br/>").html_safe + end + RUBY_EVAL + end + end + + def test_form_with_with_labelled_builder + form_with(model: @post, builder: LabelledFormBuilder) do |f| + concat f.text_field(:title) + concat f.text_area(:body) + concat f.check_box(:secret) + end + + expected = whole_form("/posts/123", method: "patch") do + "<label for='title'>Title:</label> <input name='post[title]' type='text' value='Hello World' id='post_title'/><br/>" \ + "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea><br/>" \ + "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' value='1' id='post_secret' /><br/>" + end + + assert_dom_equal expected, output_buffer + end + + def test_default_form_builder + old_default_form_builder, ActionView::Base.default_form_builder = + ActionView::Base.default_form_builder, LabelledFormBuilder + + form_with(model: @post) do |f| + concat f.text_field(:title) + concat f.text_area(:body) + concat f.check_box(:secret) + end + + expected = whole_form("/posts/123", method: "patch") do + "<label for='title'>Title:</label> <input name='post[title]' type='text' value='Hello World' id='post_title' /><br/>" \ + "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea><br/>" \ + "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' value='1' id='post_secret' /><br/>" + end + + assert_dom_equal expected, output_buffer + ensure + ActionView::Base.default_form_builder = old_default_form_builder + end + + def test_lazy_loading_default_form_builder + old_default_form_builder, ActionView::Base.default_form_builder = + ActionView::Base.default_form_builder, "FormWithActsLikeFormForTest::LabelledFormBuilder" + + form_with(model: @post) do |f| + concat f.text_field(:title) + end + + expected = whole_form("/posts/123", method: "patch") do + "<label for='title'>Title:</label> <input name='post[title]' type='text' value='Hello World' id='post_title' /><br/>" + end + + assert_dom_equal expected, output_buffer + ensure + ActionView::Base.default_form_builder = old_default_form_builder + end + + def test_form_builder_override + self.default_form_builder = LabelledFormBuilder + + output_buffer = fields(:post, model: @post) do |f| + concat f.text_field(:title) + end + + expected = "<label for='title'>Title:</label> <input name='post[title]' type='text' value='Hello World' id='post_title' /><br/>" + + assert_dom_equal expected, output_buffer + end + + def test_lazy_loading_form_builder_override + self.default_form_builder = "FormWithActsLikeFormForTest::LabelledFormBuilder" + + output_buffer = fields(:post, model: @post) do |f| + concat f.text_field(:title) + end + + expected = "<label for='title'>Title:</label> <input name='post[title]' type='text' value='Hello World' id='post_title' /><br/>" + + assert_dom_equal expected, output_buffer + end + + def test_fields_with_labelled_builder + output_buffer = fields(:post, model: @post, builder: LabelledFormBuilder) do |f| + concat f.text_field(:title) + concat f.text_area(:body) + concat f.check_box(:secret) + end + + expected = + "<label for='title'>Title:</label> <input name='post[title]' type='text' value='Hello World' id='post_title'/><br/>" \ + "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea><br/>" \ + "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' value='1' id='post_secret' /><br/>" + + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_labelled_builder_with_nested_fields_without_options_hash + klass = nil + + form_with(model: @post, builder: LabelledFormBuilder) do |f| + f.fields(:comments, model: Comment.new) do |nested_fields| + klass = nested_fields.class + "" + end + end + + assert_equal LabelledFormBuilder, klass + end + + def test_form_with_with_labelled_builder_with_nested_fields_with_options_hash + klass = nil + + form_with(model: @post, builder: LabelledFormBuilder) do |f| + f.fields(:comments, model: Comment.new, index: "foo") do |nested_fields| + klass = nested_fields.class + "" + end + end + + assert_equal LabelledFormBuilder, klass + end + + def test_form_with_with_labelled_builder_path + path = nil + + form_with(model: @post, builder: LabelledFormBuilder) do |f| + path = f.to_partial_path + "" + end + + assert_equal "labelled_form", path + end + + class LabelledFormBuilderSubclass < LabelledFormBuilder; end + + def test_form_with_with_labelled_builder_with_nested_fields_with_custom_builder + klass = nil + + form_with(model: @post, builder: LabelledFormBuilder) do |f| + f.fields(:comments, model: Comment.new, builder: LabelledFormBuilderSubclass) do |nested_fields| + klass = nested_fields.class + "" + end + end + + assert_equal LabelledFormBuilderSubclass, klass + end + + def test_form_with_with_html_options_adds_options_to_form_tag + form_with(model: @post, html: { id: "some_form", class: "some_class", multipart: true }) do |f| end + expected = whole_form("/posts/123", "some_form", "some_class", method: "patch", multipart: "multipart/form-data") + + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_string_url_option + form_with(model: @post, url: "http://www.otherdomain.com") do |f| end + + assert_dom_equal whole_form("http://www.otherdomain.com", method: "patch"), output_buffer + end + + def test_form_with_with_hash_url_option + form_with(model: @post, url: { controller: "controller", action: "action" }) do |f| end + + assert_equal "controller", @url_for_options[:controller] + assert_equal "action", @url_for_options[:action] + end + + def test_form_with_with_record_url_option + form_with(model: @post, url: @post) do |f| end + + expected = whole_form("/posts/123", method: "patch") + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_existing_object + form_with(model: @post) do |f| end + + expected = whole_form("/posts/123", method: "patch") + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_new_object + post = Post.new + post.persisted = false + def post.to_key; nil; end + + form_with(model: post) {} + + expected = whole_form("/posts") + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_existing_object_in_list + @comment.save + form_with(model: [@post, @comment]) {} + + expected = whole_form(post_comment_path(@post, @comment), method: "patch") + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_new_object_in_list + form_with(model: [@post, @comment]) {} + + expected = whole_form(post_comments_path(@post)) + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_existing_object_and_namespace_in_list + @comment.save + form_with(model: [:admin, @post, @comment]) {} + + expected = whole_form(admin_post_comment_path(@post, @comment), method: "patch") + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_new_object_and_namespace_in_list + form_with(model: [:admin, @post, @comment]) {} + + expected = whole_form(admin_post_comments_path(@post)) + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_existing_object_and_custom_url + form_with(model: @post, url: "/super_posts") do |f| end + + expected = whole_form("/super_posts", method: "patch") + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_default_method_as_patch + form_with(model: @post) {} + expected = whole_form("/posts/123", method: "patch") + assert_dom_equal expected, output_buffer + end + + def test_form_with_with_data_attributes + form_with(model: @post, data: { behavior: "stuff" }) {} + assert_match %r|data-behavior="stuff"|, output_buffer + assert_match %r|data-remote="true"|, output_buffer + end + + def test_fields_returns_block_result + output = fields(model: Post.new) { |f| "fields" } + assert_equal "fields", output + end + + def test_form_with_only_instantiates_builder_once + initialization_count = 0 + builder_class = Class.new(ActionView::Helpers::FormBuilder) do + define_method :initialize do |*args| + super(*args) + initialization_count += 1 + end + end + + form_with(model: @post, builder: builder_class) {} + assert_equal 1, initialization_count, "form builder instantiated more than once" + end + + private + def hidden_fields(options = {}) + method = options[:method] + + if options.fetch(:skip_enforcing_utf8, false) + txt = "".dup + else + txt = %{<input name="utf8" type="hidden" value="✓" />}.dup + end + + if method && !%w(get post).include?(method.to_s) + txt << %{<input name="_method" type="hidden" value="#{method}" />} + end + + txt + end + + def form_text(action = "/", id = nil, html_class = nil, local = nil, multipart = nil, method = nil) + txt = %{<form accept-charset="UTF-8" action="#{action}"}.dup + txt << %{ enctype="multipart/form-data"} if multipart + txt << %{ data-remote="true"} unless local + txt << %{ class="#{html_class}"} if html_class + txt << %{ id="#{id}"} if id + method = method.to_s == "get" ? "get" : "post" + txt << %{ method="#{method}">} + end + + def whole_form(action = "/", id = nil, html_class = nil, local: false, **options) + contents = block_given? ? yield : "" + + method, multipart = options.values_at(:method, :multipart) + + form_text(action, id, html_class, local, multipart, method) + hidden_fields(options.slice :method, :skip_enforcing_utf8) + contents + "</form>" + end + + def protect_against_forgery? + false + end + + def with_locale(testing_locale = :label) + old_locale, I18n.locale = I18n.locale, testing_locale + yield + ensure + I18n.locale = old_locale + end +end diff --git a/actionview/test/template/form_helper_test.rb b/actionview/test/template/form_helper_test.rb index 310d0ce514..6a317e1a12 100644 --- a/actionview/test/template/form_helper_test.rb +++ b/actionview/test/template/form_helper_test.rb @@ -1,11 +1,23 @@ -require 'abstract_unit' -require 'controller/fake_models' +# frozen_string_literal: true + +require "abstract_unit" +require "controller/fake_models" class FormHelperTest < ActionView::TestCase include RenderERBUtils tests ActionView::Helpers::FormHelper + class WithActiveStorageRoutesControllers < ActionController::Base + test_routes do + post "/rails/active_storage/direct_uploads" => "active_storage/direct_uploads#create", as: :rails_direct_uploads + end + + def url_options + { host: "testtwo.host" } + end + end + def form_for(*) @output_buffer = super end @@ -16,13 +28,13 @@ class FormHelperTest < ActionView::TestCase setup do # Create "label" locale for testing I18n label helpers - I18n.backend.store_translations 'label', { + I18n.backend.store_translations "label", activemodel: { attributes: { post: { cost: "Total cost" }, - :"post/language" => { + "post/language": { spanish: "Espanol" } } @@ -42,33 +54,31 @@ class FormHelperTest < ActionView::TestCase value: "Tag" }, post_delegate: { - title: 'Delegate model_name title' + title: "Delegate model_name title" } } } - } # Create "submit" locale for testing I18n submit helpers - I18n.backend.store_translations 'submit', { + I18n.backend.store_translations "submit", helpers: { submit: { - create: 'Create %{model}', - update: 'Confirm %{model} changes', - submit: 'Save changes', + create: "Create %{model}", + update: "Confirm %{model} changes", + submit: "Save changes", another_post: { - update: 'Update your %{model}' + update: "Update your %{model}" } } } - } - I18n.backend.store_translations 'placeholder', { + I18n.backend.store_translations "placeholder", activemodel: { attributes: { post: { cost: "Total cost" }, - :"post/cost" => { + "post/cost": { uk: "Pounds" } } @@ -85,18 +95,17 @@ class FormHelperTest < ActionView::TestCase } }, post_delegate: { - title: 'Delegate model_name title' + title: "Delegate model_name title" }, tag: { value: "Tag" } } } - } @post = Post.new @comment = Comment.new - def @post.errors() + def @post.errors Class.new { def [](field); field == "author_name" ? ["can't be empty"] : [] end def empty?() false end @@ -108,7 +117,7 @@ class FormHelperTest < ActionView::TestCase 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 + def @post.to_param; "123"; end @post.persisted = true @post.title = "Hello World" @@ -125,7 +134,7 @@ class FormHelperTest < ActionView::TestCase @post_delegator = PostDelegator.new - @post_delegator.title = 'Hello World' + @post_delegator.title = "Hello World" @car = Car.new("#000FFF") end @@ -178,7 +187,7 @@ class FormHelperTest < ActionView::TestCase ) assert_dom_equal( '<label class="title_label" for="post_title">Title</label>', - label("post", "title", nil, class: 'title_label') + label("post", "title", nil, class: "title_label") ) assert_dom_equal('<label for="post_secret">Secret?</label>', label("post", "secret?")) end @@ -229,7 +238,7 @@ class FormHelperTest < ActionView::TestCase def test_label_with_locales_and_nested_attributes with_locale :label do - form_for(@post, html: { id: 'create-post' }) do |f| + form_for(@post, html: { id: "create-post" }) do |f| f.fields_for(:comments) do |cf| concat cf.label(:body) end @@ -245,7 +254,7 @@ class FormHelperTest < ActionView::TestCase def test_label_with_locales_fallback_and_nested_attributes with_locale :label do - form_for(@post, html: { id: 'create-post' }) do |f| + form_for(@post, html: { id: "create-post" }) do |f| f.fields_for(:tags) do |cf| concat cf.label(:value) end @@ -260,11 +269,11 @@ class FormHelperTest < ActionView::TestCase 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| + form_for(OpenStruct.new(name: "ok"), as: "person", url: "/an", html: { id: "create-person" }) do |f| f.label(:name) end - expected = whole_form("an_url", "create-person", "new_person", method: "post") do + expected = whole_form("/an", "create-person", "new_person", method: "post") do '<label for="person_name">Name</label>' end @@ -280,7 +289,7 @@ class FormHelperTest < ActionView::TestCase end def test_label_does_not_generate_for_attribute_when_given_nil - assert_dom_equal('<label>Title</label>', label(:post, :title, for: nil)) + assert_dom_equal("<label>Title</label>", label(:post, :title, for: nil)) end def test_label_with_id_attribute_as_symbol @@ -429,7 +438,7 @@ class FormHelperTest < ActionView::TestCase def test_text_field_placeholder_with_locales_and_nested_attributes with_locale :placeholder do - form_for(@post, html: { id: 'create-post' }) do |f| + form_for(@post, html: { id: "create-post" }) do |f| f.fields_for(:comments) do |cf| concat cf.text_field(:body, placeholder: true) end @@ -445,7 +454,7 @@ class FormHelperTest < ActionView::TestCase def test_text_field_placeholder_with_locales_fallback_and_nested_attributes with_locale :placeholder do - form_for(@post, html: { id: 'create-post' }) do |f| + form_for(@post, html: { id: "create-post" }) do |f| f.fields_for(:tags) do |cf| concat cf.text_field(:value, placeholder: true) end @@ -523,39 +532,45 @@ class FormHelperTest < ActionView::TestCase end def test_text_field_doesnt_change_param_values - object_name = 'post[]' + object_name = "post[]" expected = '<input id="post_123_title" name="post[123][title]" type="text" value="Hello World" />' assert_dom_equal expected, text_field(object_name, "title") end - 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" />' + def test_file_field_has_no_size + expected = '<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) + def test_file_field_with_multiple_behavior + expected = '<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_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) + def test_file_field_with_multiple_behavior_and_explicit_name + expected = '<input id="import_file" multiple="multiple" name="custom" type="file" />' + assert_dom_equal expected, file_field("import", "file", multiple: true, name: "custom") 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") + def test_file_field_with_direct_upload_when_rails_direct_uploads_url_is_not_defined + expected = '<input type="file" name="import[file]" id="import_file" />' + assert_dom_equal expected, file_field("import", "file", direct_upload: true) end - def test_file_field_with_multiple_behavior - 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) + def test_file_field_with_direct_upload_when_rails_direct_uploads_url_is_defined + @controller = WithActiveStorageRoutesControllers.new + + expected = '<input data-direct-upload-url="http://testtwo.host/rails/active_storage/direct_uploads" type="file" name="import[file]" id="import_file" />' + assert_dom_equal expected, file_field("import", "file", direct_upload: true) end - def test_file_field_with_multiple_behavior_and_explicit_name - 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") + def test_file_field_with_direct_upload_dont_mutate_arguments + original_options = { class: "pix", direct_upload: true } + + expected = '<input class="pix" type="file" name="import[file]" id="import_file" />' + assert_dom_equal expected, file_field("import", "file", original_options) + + assert_equal({ class: "pix", direct_upload: true }, original_options) end def test_hidden_field @@ -618,7 +633,7 @@ class FormHelperTest < ActionView::TestCase def test_check_box_checked_if_option_checked_is_present assert_dom_equal( '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />', - check_box("post", "secret", "checked"=>"checked") + check_box("post", "secret", "checked" => "checked") ) end @@ -636,19 +651,19 @@ class FormHelperTest < ActionView::TestCase end def test_check_box_checked_if_object_value_includes_checked_value - @post.secret = ['0'] + @post.secret = ["0"] assert_dom_equal( '<input name="post[secret]" type="hidden" value="0" /><input id="post_secret" name="post[secret]" type="checkbox" value="1" />', check_box("post", "secret") ) - @post.secret = ['1'] + @post.secret = ["1"] assert_dom_equal( '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />', check_box("post", "secret") ) - @post.secret = Set.new(['1']) + @post.secret = Set.new(["1"]) assert_dom_equal( '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />', check_box("post", "secret") @@ -732,19 +747,19 @@ class FormHelperTest < ActionView::TestCase end def test_check_box_with_explicit_checked_and_unchecked_values_when_object_value_is_big_decimal - @post.secret = BigDecimal.new(0) + @post.secret = BigDecimal(0) assert_dom_equal( '<input name="post[secret]" type="hidden" value="1" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="0" />', check_box("post", "secret", {}, 0, 1) ) - @post.secret = BigDecimal.new(1) + @post.secret = BigDecimal(1) assert_dom_equal( '<input name="post[secret]" type="hidden" value="1" /><input id="post_secret" name="post[secret]" type="checkbox" value="0" />', check_box("post", "secret", {}, 0, 1) ) - @post.secret = BigDecimal.new(2.2, 1) + @post.secret = BigDecimal(2.2, 1) assert_dom_equal( '<input name="post[secret]" type="hidden" value="1" /><input id="post_secret" name="post[secret]" type="checkbox" value="0" />', check_box("post", "secret", {}, 0, 1) @@ -764,7 +779,7 @@ class FormHelperTest < ActionView::TestCase end def test_check_box_with_multiple_behavior - @post.comment_ids = [2,3] + @post.comment_ids = [2, 3] assert_dom_equal( '<input name="post[comment_ids][]" type="hidden" value="0" /><input id="post_comment_ids_1" name="post[comment_ids][]" type="checkbox" value="1" />', check_box("post", "comment_ids", { multiple: true }, 1) @@ -776,7 +791,7 @@ class FormHelperTest < ActionView::TestCase end def test_check_box_with_multiple_behavior_and_index - @post.comment_ids = [2,3] + @post.comment_ids = [2, 3] assert_dom_equal( '<input name="post[foo][comment_ids][]" type="hidden" value="0" /><input id="post_foo_comment_ids_1" name="post[foo][comment_ids][]" type="checkbox" value="1" />', check_box("post", "comment_ids", { multiple: true, index: "foo" }, 1) @@ -785,13 +800,12 @@ class FormHelperTest < ActionView::TestCase '<input name="post[bar][comment_ids][]" type="hidden" value="0" /><input checked="checked" id="post_bar_comment_ids_3" name="post[bar][comment_ids][]" type="checkbox" value="3" />', check_box("post", "comment_ids", { multiple: true, index: "bar" }, 3) ) - end def test_checkbox_disabled_disables_hidden_field assert_dom_equal( '<input name="post[secret]" type="hidden" value="0" disabled="disabled"/><input checked="checked" disabled="disabled" id="post_secret" name="post[secret]" type="checkbox" value="1" />', - check_box("post", "secret", { disabled: true }) + check_box("post", "secret", disabled: true) ) end @@ -826,9 +840,9 @@ class FormHelperTest < ActionView::TestCase end def test_radio_button_respects_passed_in_id - assert_dom_equal('<input checked="checked" id="foo" name="post[secret]" type="radio" value="1" />', - radio_button("post", "secret", "1", id: "foo") - ) + assert_dom_equal('<input checked="checked" id="foo" name="post[secret]" type="radio" value="1" />', + radio_button("post", "secret", "1", id: "foo") + ) end def test_radio_button_with_booleans @@ -897,7 +911,7 @@ class FormHelperTest < ActionView::TestCase def test_text_area_placeholder_with_locales_and_nested_attributes with_locale :placeholder do - form_for(@post, html: { id: 'create-post' }) do |f| + form_for(@post, html: { id: "create-post" }) do |f| f.fields_for(:comments) do |cf| concat cf.text_area(:body, placeholder: true) end @@ -913,7 +927,7 @@ class FormHelperTest < ActionView::TestCase def test_text_area_placeholder_with_locales_fallback_and_nested_attributes with_locale :placeholder do - form_for(@post, html: { id: 'create-post' }) do |f| + form_for(@post, html: { id: "create-post" }) do |f| f.fields_for(:tags) do |cf| concat cf.text_area(:value, placeholder: true) end @@ -1051,14 +1065,14 @@ class FormHelperTest < ActionView::TestCase def test_date_field_with_value_attr expected = %{<input id="post_written_on" name="post[written_on]" type="date" value="2013-06-29" />} - value = Date.new(2013,6,29) + value = Date.new(2013, 6, 29) assert_dom_equal(expected, date_field("post", "written_on", value: value)) end def test_date_field_with_timewithzone_value - previous_time_zone, Time.zone = Time.zone, 'UTC' + previous_time_zone, Time.zone = Time.zone, "UTC" expected = %{<input id="post_written_on" name="post[written_on]" type="date" value="2004-06-15" />} - @post.written_on = Time.zone.parse('2004-06-15 15:30:45') + @post.written_on = Time.zone.parse("2004-06-15 15:30:45") assert_dom_equal(expected, date_field("post", "written_on")) ensure Time.zone = previous_time_zone @@ -1107,9 +1121,9 @@ class FormHelperTest < ActionView::TestCase end def test_time_field_with_timewithzone_value - previous_time_zone, Time.zone = Time.zone, 'UTC' + previous_time_zone, Time.zone = Time.zone, "UTC" expected = %{<input id="post_written_on" name="post[written_on]" type="time" value="01:02:03.000" />} - @post.written_on = Time.zone.parse('2004-06-15 01:02:03') + @post.written_on = Time.zone.parse("2004-06-15 01:02:03") assert_dom_equal(expected, time_field("post", "written_on")) ensure Time.zone = previous_time_zone @@ -1138,76 +1152,60 @@ class FormHelperTest < ActionView::TestCase end def test_datetime_field - expected = %{<input id="post_written_on" name="post[written_on]" type="datetime" value="2004-06-15T00:00:00.000+0000" />} - assert_deprecated do - assert_dom_equal(expected, datetime_field("post", "written_on")) - end + expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" value="2004-06-15T00:00:00" />} + assert_dom_equal(expected, datetime_field("post", "written_on")) end def test_datetime_field_with_datetime_value - expected = %{<input id="post_written_on" name="post[written_on]" type="datetime" value="2004-06-15T01:02:03.000+0000" />} + expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" value="2004-06-15T01:02:03" />} @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3) - assert_deprecated do - assert_dom_equal(expected, datetime_field("post", "written_on")) - end + assert_dom_equal(expected, datetime_field("post", "written_on")) end def test_datetime_field_with_extra_attrs - expected = %{<input id="post_written_on" step="60" max="2010-08-15T10:25:00.000+0000" min="2000-06-15T20:45:30.000+0000" name="post[written_on]" type="datetime" value="2004-06-15T01:02:03.000+0000" />} + expected = %{<input id="post_written_on" step="60" max="2010-08-15T10:25:00" min="2000-06-15T20:45:30" name="post[written_on]" type="datetime-local" value="2004-06-15T01:02:03" />} @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3) min_value = DateTime.new(2000, 6, 15, 20, 45, 30) max_value = DateTime.new(2010, 8, 15, 10, 25, 00) step = 60 - assert_deprecated do - assert_dom_equal(expected, datetime_field("post", "written_on", min: min_value, max: max_value, step: step)) - end + assert_dom_equal(expected, datetime_field("post", "written_on", min: min_value, max: max_value, step: step)) end def test_datetime_field_with_value_attr - expected = %{<input id="post_written_on" name="post[written_on]" type="datetime" value="2013-06-29T13:37:00+00:00" />} - value = DateTime.new(2013,6,29,13,37) - assert_deprecated do - assert_dom_equal(expected, datetime_field("post", "written_on", value: value)) - end + expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" value="2013-06-29T13:37:00+00:00" />} + value = DateTime.new(2013, 6, 29, 13, 37) + assert_dom_equal(expected, datetime_field("post", "written_on", value: value)) end def test_datetime_field_with_timewithzone_value - previous_time_zone, Time.zone = Time.zone, 'UTC' - expected = %{<input id="post_written_on" name="post[written_on]" type="datetime" value="2004-06-15T15:30:45.000+0000" />} - @post.written_on = Time.zone.parse('2004-06-15 15:30:45') - assert_deprecated do - assert_dom_equal(expected, datetime_field("post", "written_on")) - end + previous_time_zone, Time.zone = Time.zone, "UTC" + expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" value="2004-06-15T15:30:45" />} + @post.written_on = Time.zone.parse("2004-06-15 15:30:45") + assert_dom_equal(expected, datetime_field("post", "written_on")) ensure Time.zone = previous_time_zone end def test_datetime_field_with_nil_value - expected = %{<input id="post_written_on" name="post[written_on]" type="datetime" />} + expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" />} @post.written_on = nil - assert_deprecated do - assert_dom_equal(expected, datetime_field("post", "written_on")) - end + assert_dom_equal(expected, datetime_field("post", "written_on")) end def test_datetime_field_with_string_values_for_min_and_max - expected = %{<input id="post_written_on" max="2010-08-15T10:25:00.000+0000" min="2000-06-15T20:45:30.000+0000" name="post[written_on]" type="datetime" value="2004-06-15T01:02:03.000+0000" />} + expected = %{<input id="post_written_on" max="2010-08-15T10:25:00" min="2000-06-15T20:45:30" name="post[written_on]" type="datetime-local" value="2004-06-15T01:02:03" />} @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3) - min_value = "2000-06-15T20:45:30.000+0000" - max_value = "2010-08-15T10:25:00.000+0000" - assert_deprecated do - assert_dom_equal(expected, datetime_field("post", "written_on", min: min_value, max: max_value)) - end + min_value = "2000-06-15T20:45:30" + max_value = "2010-08-15T10:25:00" + assert_dom_equal(expected, datetime_field("post", "written_on", min: min_value, max: max_value)) end def test_datetime_field_with_invalid_string_values_for_min_and_max - expected = %{<input id="post_written_on" name="post[written_on]" type="datetime" value="2004-06-15T01:02:03.000+0000" />} + expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" value="2004-06-15T01:02:03" />} @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3) min_value = "foo" max_value = "bar" - assert_deprecated do - assert_dom_equal(expected, datetime_field("post", "written_on", min: min_value, max: max_value)) - end + assert_dom_equal(expected, datetime_field("post", "written_on", min: min_value, max: max_value)) end def test_datetime_local_field @@ -1215,52 +1213,6 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal(expected, datetime_local_field("post", "written_on")) end - def test_datetime_local_field_with_datetime_value - expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" value="2004-06-15T01:02:03" />} - @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3) - assert_dom_equal(expected, datetime_local_field("post", "written_on")) - end - - def test_datetime_local_field_with_extra_attrs - expected = %{<input id="post_written_on" step="60" max="2010-08-15T10:25:00" min="2000-06-15T20:45:30" name="post[written_on]" type="datetime-local" value="2004-06-15T01:02:03" />} - @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3) - min_value = DateTime.new(2000, 6, 15, 20, 45, 30) - max_value = DateTime.new(2010, 8, 15, 10, 25, 00) - step = 60 - assert_dom_equal(expected, datetime_local_field("post", "written_on", min: min_value, max: max_value, step: step)) - end - - def test_datetime_local_field_with_timewithzone_value - previous_time_zone, Time.zone = Time.zone, 'UTC' - expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" value="2004-06-15T15:30:45" />} - @post.written_on = Time.zone.parse('2004-06-15 15:30:45') - assert_dom_equal(expected, datetime_local_field("post", "written_on")) - ensure - Time.zone = previous_time_zone - end - - def test_datetime_local_field_with_nil_value - expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" />} - @post.written_on = nil - assert_dom_equal(expected, datetime_local_field("post", "written_on")) - end - - def test_datetime_local_field_with_string_values_for_min_and_max - expected = %{<input id="post_written_on" max="2010-08-15T10:25:00" min="2000-06-15T20:45:30" name="post[written_on]" type="datetime-local" value="2004-06-15T01:02:03" />} - @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3) - min_value = "2000-06-15T20:45:30" - max_value = "2010-08-15T10:25:00" - assert_dom_equal(expected, datetime_local_field("post", "written_on", min: min_value, max: max_value)) - end - - def test_datetime_local_field_with_invalid_string_values_for_min_and_max - expected = %{<input id="post_written_on" name="post[written_on]" type="datetime-local" value="2004-06-15T01:02:03" />} - @post.written_on = DateTime.new(2004, 6, 15, 1, 2, 3) - min_value = "foo" - max_value = "bar" - assert_dom_equal(expected, datetime_local_field("post", "written_on", min: min_value, max: max_value)) - end - def test_month_field expected = %{<input id="post_written_on" name="post[written_on]" type="month" value="2004-06" />} assert_dom_equal(expected, month_field("post", "written_on")) @@ -1288,9 +1240,9 @@ class FormHelperTest < ActionView::TestCase end def test_month_field_with_timewithzone_value - previous_time_zone, Time.zone = Time.zone, 'UTC' + previous_time_zone, Time.zone = Time.zone, "UTC" expected = %{<input id="post_written_on" name="post[written_on]" type="month" value="2004-06" />} - @post.written_on = Time.zone.parse('2004-06-15 15:30:45') + @post.written_on = Time.zone.parse("2004-06-15 15:30:45") assert_dom_equal(expected, month_field("post", "written_on")) ensure Time.zone = previous_time_zone @@ -1323,9 +1275,9 @@ class FormHelperTest < ActionView::TestCase end def test_week_field_with_timewithzone_value - previous_time_zone, Time.zone = Time.zone, 'UTC' + previous_time_zone, Time.zone = Time.zone, "UTC" expected = %{<input id="post_written_on" name="post[written_on]" type="week" value="2004-W25" />} - @post.written_on = Time.zone.parse('2004-06-15 15:30:45') + @post.written_on = Time.zone.parse("2004-06-15 15:30:45") assert_dom_equal(expected, week_field("post", "written_on")) ensure Time.zone = previous_time_zone @@ -1434,7 +1386,7 @@ class FormHelperTest < ActionView::TestCase ) assert_dom_equal( '<select name="post[secret]"></select>', - select("post", "secret", [], {}, "id" => nil) + select("post", "secret", [], {}, { "id" => nil }) ) assert_dom_equal( text_field("post", "title", "id" => nil), @@ -1484,26 +1436,26 @@ class FormHelperTest < ActionView::TestCase def test_index_with_nil_id assert_dom_equal( '<input name="post[5][title]" type="text" value="Hello World" />', - text_field("post", "title", "index" => 5, 'id' => nil) + text_field("post", "title", "index" => 5, "id" => nil) ) assert_dom_equal( %{<textarea name="post[5][body]">\nBack to the hill and over it again!</textarea>}, - text_area("post", "body", "index" => 5, 'id' => nil) + text_area("post", "body", "index" => 5, "id" => nil) ) assert_dom_equal( '<input name="post[5][secret]" type="hidden" value="0" /><input checked="checked" name="post[5][secret]" type="checkbox" value="1" />', - check_box("post", "secret", "index" => 5, 'id' => nil) + check_box("post", "secret", "index" => 5, "id" => nil) ) assert_dom_equal( - text_field("post", "title", "index" => 5, 'id' => nil), + text_field("post", "title", "index" => 5, "id" => nil), text_field("post", "title", index: 5, id: nil) ) assert_dom_equal( - text_area("post", "body", "index" => 5, 'id' => nil), + text_area("post", "body", "index" => 5, "id" => nil), text_area("post", "body", index: 5, id: nil) ) assert_dom_equal( - check_box("post", "secret", "index" => 5, 'id' => nil), + check_box("post", "secret", "index" => 5, "id" => nil), check_box("post", "secret", index: 5, id: nil) ) end @@ -1516,7 +1468,7 @@ class FormHelperTest < ActionView::TestCase ) assert_dom_equal( %{<input id="post_#{pid}_title" name="post[#{pid}][title]" type="text" value="Hello World" />}, - text_field("post[]","title") + text_field("post[]", "title") ) assert_dom_equal( %{<textarea id="post_#{pid}_body" name="post[#{pid}][body]">\nBack to the hill and over it again!</textarea>}, @@ -1526,10 +1478,10 @@ class FormHelperTest < ActionView::TestCase %{<input name="post[#{pid}][secret]" type="hidden" value="0" /><input checked="checked" id="post_#{pid}_secret" name="post[#{pid}][secret]" type="checkbox" value="1" />}, check_box("post[]", "secret") ) - assert_dom_equal( + assert_dom_equal( %{<input checked="checked" id="post_#{pid}_title_hello_world" name="post[#{pid}][title]" type="radio" value="Hello World" />}, radio_button("post[]", "title", "Hello World") - ) + ) assert_dom_equal( %{<input id="post_#{pid}_title_goodbye_world" name="post[#{pid}][title]" type="radio" value="Goodbye World" />}, radio_button("post[]", "title", "Goodbye World") @@ -1550,10 +1502,10 @@ class FormHelperTest < ActionView::TestCase %{<input name="post[#{pid}][secret]" type="hidden" value="0" /><input checked="checked" name="post[#{pid}][secret]" type="checkbox" value="1" />}, check_box("post[]", "secret", id: nil) ) - assert_dom_equal( - %{<input checked="checked" name="post[#{pid}][title]" type="radio" value="Hello World" />}, - radio_button("post[]", "title", "Hello World", id: nil) - ) + assert_dom_equal( + %{<input checked="checked" name="post[#{pid}][title]" type="radio" value="Hello World" />}, + radio_button("post[]", "title", "Hello World", id: nil) + ) assert_dom_equal( %{<input name="post[#{pid}][title]" type="radio" value="Goodbye World" />}, radio_button("post[]", "title", "Goodbye World", id: nil) @@ -1562,50 +1514,82 @@ class FormHelperTest < ActionView::TestCase def test_form_for_requires_block error = assert_raises(ArgumentError) do - form_for(@post, html: { id: 'create-post' }) + form_for(@post, html: { id: "create-post" }) end assert_equal "Missing block", error.message end def test_form_for_requires_arguments error = assert_raises(ArgumentError) do - form_for(nil, html: { id: 'create-post' }) do + form_for(nil, html: { id: "create-post" }) do end end assert_equal "First argument in form cannot contain nil or be empty", error.message error = assert_raises(ArgumentError) do - form_for([nil, nil], html: { id: 'create-post' }) do + form_for([nil, nil], html: { id: "create-post" }) do end end assert_equal "First argument in form cannot contain nil or be empty", error.message end def test_form_for - form_for(@post, html: { id: 'create-post' }) do |f| + form_for(@post, html: { id: "create-post" }) do |f| + concat f.label(:title) { "The Title" } + concat f.text_field(:title) + concat f.text_area(:body) + concat f.check_box(:secret) + concat f.submit("Create post") + concat f.button("Create post") + concat f.button { + concat content_tag(:span, "Create post") + } + end + + expected = whole_form("/posts/123", "create-post", "edit_post", method: "patch") do + "<label for='post_title'>The Title</label>" \ + "<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' />" \ + "<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 + + assert_dom_equal expected, output_buffer + end + + def test_form_for_is_not_affected_by_form_with_generates_ids + old_value = ActionView::Helpers::FormHelper.form_with_generates_ids + ActionView::Helpers::FormHelper.form_with_generates_ids = false + + form_for(@post, html: { id: "create-post" }) do |f| concat f.label(:title) { "The Title" } concat f.text_field(:title) concat f.text_area(:body) concat f.check_box(:secret) - concat f.submit('Create post') - concat f.button('Create post') + concat f.submit("Create post") + concat f.button("Create post") concat f.button { - concat content_tag(:span, 'Create post') + concat content_tag(:span, "Create post") } end expected = whole_form("/posts/123", "create-post", "edit_post", method: "patch") do - "<label for='post_title'>The Title</label>" + - "<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' />" + - "<input name='commit' data-disable-with='Create post' type='submit' value='Create post' />" + - "<button name='button' type='submit'>Create post</button>" + + "<label for='post_title'>The Title</label>" \ + "<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' />" \ + "<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 assert_dom_equal expected, output_buffer + ensure + ActionView::Helpers::FormHelper.form_with_generates_ids = old_value end def test_form_for_with_collection_radio_buttons @@ -1616,10 +1600,10 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form("/posts", "new_post", "new_post") do - "<input type='hidden' name='post[active]' value='' />" + - "<input id='post_active_true' name='post[active]' type='radio' value='true' />" + - "<label for='post_active_true'>true</label>" + - "<input checked='checked' id='post_active_false' name='post[active]' type='radio' value='false' />" + + "<input type='hidden' name='post[active]' value='' />" \ + "<input id='post_active_true' name='post[active]' type='radio' value='true' />" \ + "<label for='post_active_true'>true</label>" \ + "<input checked='checked' id='post_active_false' name='post[active]' type='radio' value='false' />" \ "<label for='post_active_false'>false</label>" end @@ -1638,12 +1622,12 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form("/posts", "new_post", "new_post") do - "<input type='hidden' name='post[active]' value='' />" + - "<label for='post_active_true'>"+ - "<input id='post_active_true' name='post[active]' type='radio' value='true' />" + - "true</label>" + - "<label for='post_active_false'>"+ - "<input checked='checked' id='post_active_false' name='post[active]' type='radio' value='false' />" + + "<input type='hidden' name='post[active]' value='' />" \ + "<label for='post_active_true'>" \ + "<input id='post_active_true' name='post[active]' type='radio' value='true' />" \ + "true</label>" \ + "<label for='post_active_false'>" \ + "<input checked='checked' id='post_active_false' name='post[active]' type='radio' value='false' />" \ "false</label>" end @@ -1664,13 +1648,13 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form("/posts", "new_post_1", "new_post") do - "<input type='hidden' name='post[active]' value='' />" + - "<label for='post_active_true'>"+ - "<input id='post_active_true' name='post[active]' type='radio' value='true' />" + - "true</label>" + - "<label for='post_active_false'>"+ - "<input checked='checked' id='post_active_false' name='post[active]' type='radio' value='false' />" + - "false</label>"+ + "<input type='hidden' name='post[active]' value='' />" \ + "<label for='post_active_true'>" \ + "<input id='post_active_true' name='post[active]' type='radio' value='true' />" \ + "true</label>" \ + "<label for='post_active_false'>" \ + "<input checked='checked' id='post_active_false' name='post[active]' type='radio' value='false' />" \ + "false</label>" \ "<input id='post_id' name='post[id]' type='hidden' value='1' />" end @@ -1681,15 +1665,15 @@ class FormHelperTest < ActionView::TestCase post = Post.new def post.active; false; end - form_for(post, namespace: 'foo') do |f| + form_for(post, namespace: "foo") do |f| concat f.collection_radio_buttons(:active, [true, false], :to_s, :to_s) end expected = whole_form("/posts", "foo_new_post", "new_post") do - "<input type='hidden' name='post[active]' value='' />" + - "<input id='foo_post_active_true' name='post[active]' type='radio' value='true' />" + - "<label for='foo_post_active_true'>true</label>" + - "<input checked='checked' id='foo_post_active_false' name='post[active]' type='radio' value='false' />" + + "<input type='hidden' name='post[active]' value='' />" \ + "<input id='foo_post_active_true' name='post[active]' type='radio' value='true' />" \ + "<label for='foo_post_active_true'>true</label>" \ + "<input checked='checked' id='foo_post_active_false' name='post[active]' type='radio' value='false' />" \ "<label for='foo_post_active_false'>false</label>" end @@ -1700,15 +1684,15 @@ class FormHelperTest < ActionView::TestCase post = Post.new def post.active; false; end - form_for(post, index: '1') do |f| + form_for(post, index: "1") do |f| concat f.collection_radio_buttons(:active, [true, false], :to_s, :to_s) end expected = whole_form("/posts", "new_post", "new_post") do - "<input type='hidden' name='post[1][active]' value='' />" + - "<input id='post_1_active_true' name='post[1][active]' type='radio' value='true' />" + - "<label for='post_1_active_true'>true</label>" + - "<input checked='checked' id='post_1_active_false' name='post[1][active]' type='radio' value='false' />" + + "<input type='hidden' name='post[1][active]' value='' />" \ + "<input id='post_1_active_true' name='post[1][active]' type='radio' value='true' />" \ + "<label for='post_1_active_true'>true</label>" \ + "<input checked='checked' id='post_1_active_false' name='post[1][active]' type='radio' value='false' />" \ "<label for='post_1_active_false'>false</label>" end @@ -1724,12 +1708,12 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form("/posts", "new_post", "new_post") do - "<input name='post[tag_ids][]' type='hidden' value='' />" + - "<input checked='checked' id='post_tag_ids_1' name='post[tag_ids][]' type='checkbox' value='1' />" + - "<label for='post_tag_ids_1'>Tag 1</label>" + - "<input id='post_tag_ids_2' name='post[tag_ids][]' type='checkbox' value='2' />" + - "<label for='post_tag_ids_2'>Tag 2</label>" + - "<input checked='checked' id='post_tag_ids_3' name='post[tag_ids][]' type='checkbox' value='3' />" + + "<input name='post[tag_ids][]' type='hidden' value='' />" \ + "<input checked='checked' id='post_tag_ids_1' name='post[tag_ids][]' type='checkbox' value='1' />" \ + "<label for='post_tag_ids_1'>Tag 1</label>" \ + "<input id='post_tag_ids_2' name='post[tag_ids][]' type='checkbox' value='2' />" \ + "<label for='post_tag_ids_2'>Tag 2</label>" \ + "<input checked='checked' id='post_tag_ids_3' name='post[tag_ids][]' type='checkbox' value='3' />" \ "<label for='post_tag_ids_3'>Tag 3</label>" end @@ -1748,15 +1732,15 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form("/posts", "new_post", "new_post") do - "<input name='post[tag_ids][]' type='hidden' value='' />" + - "<label for='post_tag_ids_1'>" + - "<input checked='checked' id='post_tag_ids_1' name='post[tag_ids][]' type='checkbox' value='1' />" + - "Tag 1</label>" + - "<label for='post_tag_ids_2'>" + - "<input id='post_tag_ids_2' name='post[tag_ids][]' type='checkbox' value='2' />" + - "Tag 2</label>" + - "<label for='post_tag_ids_3'>" + - "<input checked='checked' id='post_tag_ids_3' name='post[tag_ids][]' type='checkbox' value='3' />" + + "<input name='post[tag_ids][]' type='hidden' value='' />" \ + "<label for='post_tag_ids_1'>" \ + "<input checked='checked' id='post_tag_ids_1' name='post[tag_ids][]' type='checkbox' value='1' />" \ + "Tag 1</label>" \ + "<label for='post_tag_ids_2'>" \ + "<input id='post_tag_ids_2' name='post[tag_ids][]' type='checkbox' value='2' />" \ + "Tag 2</label>" \ + "<label for='post_tag_ids_3'>" \ + "<input checked='checked' id='post_tag_ids_3' name='post[tag_ids][]' type='checkbox' value='3' />" \ "Tag 3</label>" end @@ -1778,16 +1762,16 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form("/posts", "new_post_1", "new_post") do - "<input name='post[tag_ids][]' type='hidden' value='' />"+ - "<label for='post_tag_ids_1'>" + - "<input checked='checked' id='post_tag_ids_1' name='post[tag_ids][]' type='checkbox' value='1' />" + - "Tag 1</label>" + - "<label for='post_tag_ids_2'>" + - "<input id='post_tag_ids_2' name='post[tag_ids][]' type='checkbox' value='2' />" + - "Tag 2</label>" + - "<label for='post_tag_ids_3'>" + - "<input checked='checked' id='post_tag_ids_3' name='post[tag_ids][]' type='checkbox' value='3' />" + - "Tag 3</label>" + + "<input name='post[tag_ids][]' type='hidden' value='' />" \ + "<label for='post_tag_ids_1'>" \ + "<input checked='checked' id='post_tag_ids_1' name='post[tag_ids][]' type='checkbox' value='1' />" \ + "Tag 1</label>" \ + "<label for='post_tag_ids_2'>" \ + "<input id='post_tag_ids_2' name='post[tag_ids][]' type='checkbox' value='2' />" \ + "Tag 2</label>" \ + "<label for='post_tag_ids_3'>" \ + "<input checked='checked' id='post_tag_ids_3' name='post[tag_ids][]' type='checkbox' value='3' />" \ + "Tag 3</label>" \ "<input id='post_id' name='post[id]' type='hidden' value='1' />" end @@ -1799,13 +1783,13 @@ class FormHelperTest < ActionView::TestCase def post.tag_ids; [1]; end collection = [[1, "Tag 1"]] - form_for(post, namespace: 'foo') do |f| + form_for(post, namespace: "foo") do |f| concat f.collection_check_boxes(:tag_ids, collection, :first, :last) end expected = whole_form("/posts", "foo_new_post", "new_post") do - "<input name='post[tag_ids][]' type='hidden' value='' />" + - "<input checked='checked' id='foo_post_tag_ids_1' name='post[tag_ids][]' type='checkbox' value='1' />" + + "<input name='post[tag_ids][]' type='hidden' value='' />" \ + "<input checked='checked' id='foo_post_tag_ids_1' name='post[tag_ids][]' type='checkbox' value='1' />" \ "<label for='foo_post_tag_ids_1'>Tag 1</label>" end @@ -1817,13 +1801,13 @@ class FormHelperTest < ActionView::TestCase def post.tag_ids; [1]; end collection = [[1, "Tag 1"]] - form_for(post, index: '1') do |f| + form_for(post, index: "1") do |f| concat f.collection_check_boxes(:tag_ids, collection, :first, :last) end expected = whole_form("/posts", "new_post", "new_post") do - "<input name='post[1][tag_ids][]' type='hidden' value='' />" + - "<input checked='checked' id='post_1_tag_ids_1' name='post[1][tag_ids][]' type='checkbox' value='1' />" + + "<input name='post[1][tag_ids][]' type='hidden' value='' />" \ + "<input checked='checked' id='post_1_tag_ids_1' name='post[1][tag_ids][]' type='checkbox' value='1' />" \ "<label for='post_1_tag_ids_1'>Tag 1</label>" end @@ -1831,22 +1815,18 @@ class FormHelperTest < ActionView::TestCase end def test_form_for_with_file_field_generate_multipart - Post.send :attr_accessor, :file - - form_for(@post, html: { id: 'create-post' }) do |f| + form_for(@post, html: { id: "create-post" }) do |f| concat f.file_field(:file) end expected = whole_form("/posts/123", "create-post", "edit_post", method: "patch", multipart: true) do - "<input name='post[file]' type='hidden' value='' /><input name='post[file]' type='file' id='post_file' />" + "<input name='post[file]' type='file' id='post_file' />" end assert_dom_equal expected, output_buffer end def test_fields_for_with_file_field_generate_multipart - Comment.send :attr_accessor, :file - form_for(@post) do |f| concat f.fields_for(:comment, @post) { |c| concat c.file_field(:file) @@ -1854,7 +1834,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='hidden' value='' /><input name='post[comment][file]' type='file' id='post_comment_file' />" + "<input name='post[comment][file]' type='file' id='post_comment_file' />" end assert_dom_equal expected, output_buffer @@ -1865,7 +1845,7 @@ class FormHelperTest < ActionView::TestCase concat f.label(:title) end - expected = whole_form("/posts/123.json", "edit_post_123", "edit_post", method: 'patch') do + expected = whole_form("/posts/123.json", "edit_post_123", "edit_post", method: "patch") do "<label for='post_title'>Title</label>" end @@ -1877,32 +1857,32 @@ class FormHelperTest < ActionView::TestCase form_for(blog_post) do |f| concat f.text_field :title - concat f.submit('Edit post') + concat f.submit("Edit post") end 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='post[title]' type='text' id='post_title' value='And his name will be forty and four.' />" \ "<input name='commit' data-disable-with='Edit post' type='submit' value='Edit post' />" end assert_dom_equal expected, output_buffer end - def test_form_for_with_symbol_object_name + def test_form_for_with_symbol_as form_for(@post, as: "other_name", html: { id: "create-post" }) do |f| - concat f.label(:title, class: 'post_title') + concat f.label(:title, class: "post_title") concat f.text_field(:title) concat f.text_area(:body) concat f.check_box(:secret) - concat f.submit('Create post') + concat f.submit("Create post") end - expected = whole_form("/posts/123", "create-post", "edit_other_name", method: "patch") do - "<label for='other_name_title' class='post_title'>Title</label>" + - "<input name='other_name[title]' id='other_name_title' value='Hello World' type='text' />" + - "<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' />" + + expected = whole_form("/posts/123", "create-post", "edit_other_name", method: "patch") do + "<label for='other_name_title' class='post_title'>Title</label>" \ + "<input name='other_name[title]' id='other_name_title' value='Hello World' type='text' />" \ + "<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' data-disable-with='Create post' type='submit' />" end @@ -1913,27 +1893,27 @@ class FormHelperTest < ActionView::TestCase obj = Class.new do private - def private_property - raise "This method should not be called." - end + 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| + 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| + form_for(@post, url: "/", html: { id: "create-post", method: :delete }) do |f| concat f.text_field(:title) concat f.text_area(:body) concat f.check_box(:secret) end - expected = whole_form("/", "create-post", "edit_post", method: "delete") 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' />" + + expected = whole_form("/", "create-post", "edit_post", method: "delete") 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 @@ -1941,16 +1921,16 @@ class FormHelperTest < ActionView::TestCase end def test_form_for_with_method - form_for(@post, url: '/', method: :delete, html: { id: 'create-post' }) do |f| + form_for(@post, url: "/", method: :delete, html: { id: "create-post" }) do |f| concat f.text_field(:title) concat f.text_area(:body) concat f.check_box(:secret) end - expected = whole_form("/", "create-post", "edit_post", method: "delete") 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' />" + + expected = whole_form("/", "create-post", "edit_post", method: "delete") 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 @@ -1964,7 +1944,7 @@ class FormHelperTest < ActionView::TestCase concat f.search_field(:title) end - expected = whole_form("/search", "search-post", "new_post", method: "get") do + expected = whole_form("/search", "search-post", "new_post", method: "get") do "<input name='post[title]' type='search' id='post_title' />" end @@ -1972,16 +1952,16 @@ class FormHelperTest < ActionView::TestCase end def test_form_for_with_remote - form_for(@post, url: '/', remote: true, html: { id: 'create-post', method: :patch }) do |f| + form_for(@post, url: "/", remote: true, html: { id: "create-post", method: :patch }) do |f| concat f.text_field(:title) concat f.text_area(:body) concat f.check_box(:secret) end - expected = whole_form("/", "create-post", "edit_post", method: "patch", 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' />" + + expected = whole_form("/", "create-post", "edit_post", method: "patch", 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 @@ -2013,16 +1993,16 @@ class FormHelperTest < ActionView::TestCase end def test_form_for_with_remote_in_html - form_for(@post, url: '/', html: { remote: true, id: 'create-post', method: :patch }) do |f| + form_for(@post, url: "/", html: { remote: true, id: "create-post", method: :patch }) do |f| concat f.text_field(:title) concat f.text_area(:body) concat f.check_box(:secret) end - expected = whole_form("/", "create-post", "edit_post", method: "patch", 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' />" + + expected = whole_form("/", "create-post", "edit_post", method: "patch", 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 @@ -2038,10 +2018,10 @@ class FormHelperTest < ActionView::TestCase 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' />" + + 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 @@ -2050,16 +2030,16 @@ class FormHelperTest < ActionView::TestCase end def test_form_for_without_object - form_for(:post, html: { id: 'create-post' }) do |f| + form_for(:post, html: { id: "create-post" }) do |f| concat f.text_field(:title) concat f.text_area(:body) concat f.check_box(:secret) end expected = whole_form("/", "create-post") 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[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 @@ -2074,11 +2054,11 @@ class FormHelperTest < ActionView::TestCase concat f.check_box(:secret) end - expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', method: 'patch') do - "<label for='post_123_title'>Title</label>" + - "<input name='post[123][title]' type='text' id='post_123_title' value='Hello World' />" + - "<textarea name='post[123][body]' id='post_123_body'>\nBack to the hill and over it again!</textarea>" + - "<input name='post[123][secret]' type='hidden' value='0' />" + + expected = whole_form("/posts/123", "edit_post[]", "edit_post[]", method: "patch") do + "<label for='post_123_title'>Title</label>" \ + "<input name='post[123][title]' type='text' id='post_123_title' value='Hello World' />" \ + "<textarea name='post[123][body]' id='post_123_body'>\nBack to the hill and over it again!</textarea>" \ + "<input name='post[123][secret]' type='hidden' value='0' />" \ "<input name='post[123][secret]' checked='checked' type='checkbox' id='post_123_secret' value='1' />" end @@ -2092,10 +2072,10 @@ class FormHelperTest < ActionView::TestCase concat f.check_box(:secret) end - expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', method: 'patch') 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' />" + + expected = whole_form("/posts/123", "edit_post[]", "edit_post[]", method: "patch") 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 @@ -2104,14 +2084,14 @@ class FormHelperTest < ActionView::TestCase def test_form_for_label_error_wrapping form_for(@post) do |f| - concat f.label(:author_name, class: 'label') + concat f.label(:author_name, class: "label") concat f.text_field(:author_name) - concat f.submit('Create post') + concat f.submit("Create post") end - 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>" + + 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' data-disable-with='Create post' type='submit' value='Create post' />" end @@ -2122,14 +2102,14 @@ class FormHelperTest < ActionView::TestCase post = remove_instance_variable :@post form_for(post) do |f| - concat f.label(:author_name, class: 'label') + concat f.label(:author_name, class: "label") concat f.text_field(:author_name) - concat f.submit('Create post') + concat f.submit("Create post") end - 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>" + + 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' data-disable-with='Create post' type='submit' value='Create post' />" end @@ -2138,12 +2118,12 @@ class FormHelperTest < ActionView::TestCase def test_form_for_label_error_wrapping_block_and_non_block_versions form_for(@post) do |f| - concat f.label(:author_name, 'Name', class: 'label') - concat f.label(:author_name, class: 'label') { 'Name' } + concat f.label(:author_name, "Name", class: "label") + concat f.label(:author_name, class: "label") { "Name" } end - 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'>Name</label></div>" + + 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'>Name</label></div>" \ "<div class='field_with_errors'><label for='post_author_name' class='label'>Name</label></div>" end @@ -2151,16 +2131,16 @@ class FormHelperTest < ActionView::TestCase end def test_form_for_with_namespace - form_for(@post, namespace: 'namespace') do |f| + form_for(@post, namespace: "namespace") do |f| concat f.text_field(:title) concat f.text_area(:body) concat f.check_box(:secret) end - expected = whole_form('/posts/123', 'namespace_edit_post_123', 'edit_post', method: 'patch') do - "<input name='post[title]' type='text' id='namespace_post_title' value='Hello World' />" + - "<textarea name='post[body]' id='namespace_post_body'>\nBack to the hill and over it again!</textarea>" + - "<input name='post[secret]' type='hidden' value='0' />" + + expected = whole_form("/posts/123", "namespace_edit_post_123", "edit_post", method: "patch") do + "<input name='post[title]' type='text' id='namespace_post_title' value='Hello World' />" \ + "<textarea name='post[body]' id='namespace_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='namespace_post_secret' value='1' />" end @@ -2168,21 +2148,21 @@ class FormHelperTest < ActionView::TestCase end def test_form_for_with_namespace_with_date_select - form_for(@post, namespace: 'namespace') do |f| + form_for(@post, namespace: "namespace") do |f| concat f.date_select(:written_on) end - assert_select 'select#namespace_post_written_on_1i' + assert_select "select#namespace_post_written_on_1i" end def test_form_for_with_namespace_with_label - form_for(@post, namespace: 'namespace') do |f| + form_for(@post, namespace: "namespace") do |f| concat f.label(:title) concat f.text_field(:title) end - expected = whole_form('/posts/123', 'namespace_edit_post_123', 'edit_post', method: 'patch') do - "<label for='namespace_post_title'>Title</label>" + + expected = whole_form("/posts/123", "namespace_edit_post_123", "edit_post", method: "patch") do + "<label for='namespace_post_title'>Title</label>" \ "<input name='post[title]' type='text' id='namespace_post_title' value='Hello World' />" end @@ -2190,11 +2170,11 @@ class FormHelperTest < ActionView::TestCase end def test_form_for_with_namespace_and_as_option - form_for(@post, namespace: 'namespace', as: 'custom_name') do |f| + form_for(@post, namespace: "namespace", as: "custom_name") do |f| concat f.text_field(:title) end - expected = whole_form('/posts/123', 'namespace_edit_custom_name', 'edit_custom_name', method: 'patch') do + expected = whole_form("/posts/123", "namespace_edit_custom_name", "edit_custom_name", method: "patch") do "<input id='namespace_custom_name_title' name='custom_name[title]' type='text' value='Hello World' />" end @@ -2202,25 +2182,25 @@ class FormHelperTest < ActionView::TestCase end def test_two_form_for_with_namespace - form_for(@post, namespace: 'namespace_1') do |f| + form_for(@post, namespace: "namespace_1") do |f| concat f.label(:title) concat f.text_field(:title) end - expected_1 = whole_form('/posts/123', 'namespace_1_edit_post_123', 'edit_post', method: 'patch') do - "<label for='namespace_1_post_title'>Title</label>" + + expected_1 = whole_form("/posts/123", "namespace_1_edit_post_123", "edit_post", method: "patch") do + "<label for='namespace_1_post_title'>Title</label>" \ "<input name='post[title]' type='text' id='namespace_1_post_title' value='Hello World' />" end assert_dom_equal expected_1, output_buffer - form_for(@post, namespace: 'namespace_2') do |f| + form_for(@post, namespace: "namespace_2") do |f| concat f.label(:title) concat f.text_field(:title) end - expected_2 = whole_form('/posts/123', 'namespace_2_edit_post_123', 'edit_post', method: 'patch') do - "<label for='namespace_2_post_title'>Title</label>" + + expected_2 = whole_form("/posts/123", "namespace_2_edit_post_123", "edit_post", method: "patch") do + "<label for='namespace_2_post_title'>Title</label>" \ "<input name='post[title]' type='text' id='namespace_2_post_title' value='Hello World' />" end @@ -2228,8 +2208,8 @@ class FormHelperTest < ActionView::TestCase end def test_fields_for_with_namespace - @comment.body = 'Hello World' - form_for(@post, namespace: 'namespace') do |f| + @comment.body = "Hello World" + form_for(@post, namespace: "namespace") do |f| concat f.text_field(:title) concat f.text_area(:body) concat f.fields_for(@comment) { |c| @@ -2237,9 +2217,9 @@ class FormHelperTest < ActionView::TestCase } end - expected = whole_form('/posts/123', 'namespace_edit_post_123', 'edit_post', method: 'patch') do - "<input name='post[title]' type='text' id='namespace_post_title' value='Hello World' />" + - "<textarea name='post[body]' id='namespace_post_body'>\nBack to the hill and over it again!</textarea>" + + expected = whole_form("/posts/123", "namespace_edit_post_123", "edit_post", method: "patch") do + "<input name='post[title]' type='text' id='namespace_post_title' value='Hello World' />" \ + "<textarea name='post[body]' id='namespace_post_body'>\nBack to the hill and over it again!</textarea>" \ "<input name='post[comment][body]' type='text' id='namespace_post_comment_body' value='Hello World' />" end @@ -2254,7 +2234,7 @@ class FormHelperTest < ActionView::TestCase concat f.submit end - expected = whole_form('/posts', 'new_post', 'new_post') do + expected = whole_form("/posts", "new_post", "new_post") do "<input name='commit' data-disable-with='Create Post' type='submit' value='Create Post' />" end @@ -2269,8 +2249,8 @@ class FormHelperTest < ActionView::TestCase concat f.submit end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - "<input name='commit' data-disable-with='Confirm Post changes' type='submit' value='Confirm Post changes' />" + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + "<input name='commit' data-disable-with='Confirm Post changes' type='submit' value='Confirm Post changes' />" end assert_dom_equal expected, output_buffer @@ -2284,7 +2264,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form do - "<input name='commit' class='extra' data-disable-with='Save changes' 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 @@ -2297,8 +2277,8 @@ class FormHelperTest < ActionView::TestCase concat f.submit end - expected = whole_form('/posts/123', 'edit_another_post', 'edit_another_post', method: 'patch') do - "<input name='commit' data-disable-with='Update your Post' type='submit' value='Update your Post' />" + expected = whole_form("/posts/123", "edit_another_post", "edit_another_post", method: "patch") do + "<input name='commit' data-disable-with='Update your Post' type='submit' value='Update your Post' />" end assert_dom_equal expected, output_buffer @@ -2306,14 +2286,14 @@ class FormHelperTest < ActionView::TestCase end def test_nested_fields_for - @comment.body = 'Hello World' + @comment.body = "Hello World" form_for(@post) do |f| concat f.fields_for(@comment) { |c| concat c.text_field(:body) } end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do "<input name='post[comment][body]' type='text' id='post_comment_body' value='Hello World' />" end @@ -2323,10 +2303,10 @@ class FormHelperTest < ActionView::TestCase def test_deep_nested_fields_for @comment.save form_for(:posts) do |f| - f.fields_for('post[]', @post) do |f2| + f.fields_for("post[]", @post) do |f2| f2.text_field(:id) @post.comments.each do |comment| - concat f2.fields_for('comment[]', comment) { |c| + concat f2.fields_for("comment[]", comment) { |c| concat c.text_field(:name) } end @@ -2340,18 +2320,19 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal expected, output_buffer end - def test_nested_fields_for_with_nested_collections - form_for(@post, as: 'post[]') do |f| + form_for(@post, as: "post[]") do |f| concat f.text_field(:title) - concat f.fields_for('comment[]', @comment) { |c| + concat f.fields_for("comment[]", @comment) { |c| concat c.text_field(:name) } + concat f.text_field(:body) end - expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', method: 'patch') do - "<input name='post[123][title]' type='text' id='post_123_title' value='Hello World' />" + - "<input name='post[123][comment][][name]' type='text' id='post_123_comment__name' value='new comment' />" + expected = whole_form("/posts/123", "edit_post[]", "edit_post[]", method: "patch") do + "<input name='post[123][title]' type='text' id='post_123_title' value='Hello World' />" \ + "<input name='post[123][comment][][name]' type='text' id='post_123_comment__name' value='new comment' />" \ + "<input name='post[123][body]' type='text' id='post_123_body' value='Back to the hill and over it again!' />" end assert_dom_equal expected, output_buffer @@ -2360,13 +2341,13 @@ class FormHelperTest < ActionView::TestCase def test_nested_fields_for_with_index_and_parent_fields form_for(@post, index: 1) do |c| concat c.text_field(:title) - concat c.fields_for('comment', @comment, index: 1) { |r| + concat c.fields_for("comment", @comment, index: 1) { |r| concat r.text_field(:name) } end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - "<input name='post[1][title]' type='text' id='post_1_title' value='Hello World' />" + + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + "<input name='post[1][title]' type='text' id='post_1_title' value='Hello World' />" \ "<input name='post[1][comment][1][name]' type='text' id='post_1_comment_1_name' value='new comment' />" end @@ -2380,7 +2361,7 @@ class FormHelperTest < ActionView::TestCase } end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do "<input name='post[1][comment][title]' type='text' id='post_1_comment_title' value='Hello World' />" end @@ -2394,7 +2375,7 @@ class FormHelperTest < ActionView::TestCase } end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do "<input name='post[1][comment][5][title]' type='text' id='post_1_comment_5_title' value='Hello World' />" end @@ -2408,7 +2389,7 @@ class FormHelperTest < ActionView::TestCase } end - expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', method: 'patch') do + expected = whole_form("/posts/123", "edit_post[]", "edit_post[]", method: "patch") do "<input name='post[123][comment][title]' type='text' id='post_123_comment_title' value='Hello World' />" end @@ -2422,7 +2403,7 @@ class FormHelperTest < ActionView::TestCase } end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do "<input name='post[comment][5][title]' type='radio' id='post_comment_5_title_hello' value='hello' />" end @@ -2436,7 +2417,7 @@ class FormHelperTest < ActionView::TestCase } end - expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', method: 'patch') do + expected = whole_form("/posts/123", "edit_post[]", "edit_post[]", method: "patch") do "<input name='post[123][comment][123][title]' type='text' id='post_123_comment_123_title' value='Hello World' />" end @@ -2456,9 +2437,9 @@ class FormHelperTest < ActionView::TestCase } end - expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', method: 'patch') do + expected = whole_form("/posts/123", "edit_post[]", "edit_post[]", method: "patch") do "<input name='post[123][comment][5][title]' type='text' id='post_123_comment_5_title' value='Hello World' />" - end + whole_form('/posts/123', 'edit_post', 'edit_post', method: 'patch') do + end + whole_form("/posts/123", "edit_post", "edit_post", method: "patch") do "<input name='post[1][comment][123][title]' type='text' id='post_1_comment_123_title' value='Hello World' />" end @@ -2475,8 +2456,8 @@ class FormHelperTest < ActionView::TestCase } end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' \ '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="new author" />' end @@ -2502,11 +2483,11 @@ class FormHelperTest < ActionView::TestCase } end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + - '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' + - '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' - end + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' \ + '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' \ + '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' + end assert_dom_equal expected, output_buffer end @@ -2521,9 +2502,9 @@ class FormHelperTest < ActionView::TestCase } end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + - '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' + + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' \ + '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' \ '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' end @@ -2540,8 +2521,8 @@ class FormHelperTest < ActionView::TestCase } end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' \ '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' end @@ -2558,8 +2539,8 @@ class FormHelperTest < ActionView::TestCase } end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' \ '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' end @@ -2576,9 +2557,9 @@ class FormHelperTest < ActionView::TestCase } end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + - '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' + + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' \ + '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' \ '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' end @@ -2596,9 +2577,9 @@ class FormHelperTest < ActionView::TestCase } end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + - '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' + + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' \ + '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' \ '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' end @@ -2617,11 +2598,11 @@ class FormHelperTest < ActionView::TestCase end end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + - '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' + + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' \ + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' \ + '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' \ + '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' \ '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />' end @@ -2644,11 +2625,11 @@ class FormHelperTest < ActionView::TestCase end end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + - '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' + - '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' \ + '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' \ + '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' \ + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' \ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' end @@ -2671,10 +2652,10 @@ class FormHelperTest < ActionView::TestCase end end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + - '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' \ + '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' \ + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' \ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' end @@ -2697,11 +2678,11 @@ class FormHelperTest < ActionView::TestCase end end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + - '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' + - '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' \ + '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="author #321" />' \ + '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' \ + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' \ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' end @@ -2720,11 +2701,11 @@ class FormHelperTest < ActionView::TestCase end end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + - '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' + + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' \ + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' \ + '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' \ + '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' \ '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />' end @@ -2744,11 +2725,11 @@ class FormHelperTest < ActionView::TestCase end end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + - '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />' + + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' \ + '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' \ + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' \ + '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />' \ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' end @@ -2767,9 +2748,9 @@ class FormHelperTest < ActionView::TestCase end end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="new comment" />' + + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' \ + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="new comment" />' \ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="new comment" />' end @@ -2788,10 +2769,10 @@ class FormHelperTest < ActionView::TestCase end end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #321" />' + - '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="321" />' + + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' \ + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #321" />' \ + '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="321" />' \ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="new comment" />' end @@ -2806,7 +2787,7 @@ class FormHelperTest < ActionView::TestCase end end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do '<input name="post[title]" type="text" id="post_title" value="Hello World" />' end @@ -2823,11 +2804,11 @@ class FormHelperTest < ActionView::TestCase } end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + - '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' + + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' \ + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' \ + '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' \ + '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' \ '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />' end @@ -2844,11 +2825,11 @@ class FormHelperTest < ActionView::TestCase } end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + - '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' + + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' \ + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' \ + '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' \ + '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' \ '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />' end @@ -2858,7 +2839,7 @@ 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) } - params = 11.times.map { ['post.comments.body', default: [:"comment.body", ''], scope: "helpers.label"] } + 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| @@ -2879,11 +2860,11 @@ class FormHelperTest < ActionView::TestCase } end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + - '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' + + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' \ + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #1" />' \ + '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' \ + '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="comment #2" />' \ '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />' end @@ -2902,10 +2883,10 @@ class FormHelperTest < ActionView::TestCase } end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - '<input name="post[title]" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #321" />' + - '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="321" />' + + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + '<input name="post[title]" type="text" id="post_title" value="Hello World" />' \ + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #321" />' \ + '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="321" />' \ '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" type="text" value="new comment" />' end @@ -2917,13 +2898,13 @@ class FormHelperTest < ActionView::TestCase @post.comments = [] form_for(@post) do |f| - concat f.fields_for(:comments, Comment.new(321), child_index: 'abc') { |cf| + 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" />' + + 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 @@ -2934,13 +2915,13 @@ class FormHelperTest < ActionView::TestCase @post.comments = [] form_for(@post) do |f| - concat f.fields_for(:comments, Comment.new(321), child_index: -> { 'abc' } ) { |cf| + 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" />' + + 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 @@ -2957,13 +2938,13 @@ class FormHelperTest < ActionView::TestCase @post.comments = FakeAssociationProxy.new form_for(@post) do |f| - concat f.fields_for(:comments, Comment.new(321), child_index: 'abc') { |cf| + 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" />' + + 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 @@ -2977,7 +2958,7 @@ class FormHelperTest < ActionView::TestCase expected = 0 @post.comments.each do |comment| f.fields_for(:comments, comment) { |cf| - assert_equal cf.index, expected + assert_equal expected, cf.index expected += 1 } end @@ -2991,7 +2972,7 @@ class FormHelperTest < ActionView::TestCase expected = 0 @post.comments.each do |comment| f.fields_for(:comments, comment) { |cf| - assert_equal cf.index, expected + assert_equal expected, cf.index expected += 1 } end @@ -3004,7 +2985,7 @@ class FormHelperTest < ActionView::TestCase form_for(@post) do |f| expected = 0 f.fields_for(:comments, @post.comments) { |cf| - assert_equal cf.index, expected + assert_equal expected, cf.index expected += 1 } end @@ -3014,8 +2995,8 @@ class FormHelperTest < ActionView::TestCase @post.comments = [] form_for(@post) do |f| - f.fields_for(:comments, Comment.new(321), child_index: 'abc') { |cf| - assert_equal cf.index, 'abc' + f.fields_for(:comments, Comment.new(321), child_index: "abc") { |cf| + assert_equal "abc", cf.index } end end @@ -3040,7 +3021,7 @@ class FormHelperTest < ActionView::TestCase concat trf.text_field(:value) } } - concat f.fields_for('tags', @post.tags[1]) { |tf| + concat f.fields_for("tags", @post.tags[1]) { |tf| concat tf.text_field(:value) concat tf.fields_for(:relevances, TagRelevance.new(31415)) { |trf| concat trf.text_field(:value) @@ -3048,18 +3029,18 @@ class FormHelperTest < ActionView::TestCase } end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #321" />' + - '<input id="post_comments_attributes_0_relevances_attributes_0_value" name="post[comments_attributes][0][relevances_attributes][0][value]" type="text" value="commentrelevance #314" />' + - '<input id="post_comments_attributes_0_relevances_attributes_0_id" name="post[comments_attributes][0][relevances_attributes][0][id]" type="hidden" value="314" />' + - '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="321" />' + - '<input id="post_tags_attributes_0_value" name="post[tags_attributes][0][value]" type="text" value="tag #123" />' + - '<input id="post_tags_attributes_0_relevances_attributes_0_value" name="post[tags_attributes][0][relevances_attributes][0][value]" type="text" value="tagrelevance #3141" />' + - '<input id="post_tags_attributes_0_relevances_attributes_0_id" name="post[tags_attributes][0][relevances_attributes][0][id]" type="hidden" value="3141" />' + - '<input id="post_tags_attributes_0_id" name="post[tags_attributes][0][id]" type="hidden" value="123" />' + - '<input id="post_tags_attributes_1_value" name="post[tags_attributes][1][value]" type="text" value="tag #456" />' + - '<input id="post_tags_attributes_1_relevances_attributes_0_value" name="post[tags_attributes][1][relevances_attributes][0][value]" type="text" value="tagrelevance #31415" />' + - '<input id="post_tags_attributes_1_relevances_attributes_0_id" name="post[tags_attributes][1][relevances_attributes][0][id]" type="hidden" value="31415" />' + + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" type="text" value="comment #321" />' \ + '<input id="post_comments_attributes_0_relevances_attributes_0_value" name="post[comments_attributes][0][relevances_attributes][0][value]" type="text" value="commentrelevance #314" />' \ + '<input id="post_comments_attributes_0_relevances_attributes_0_id" name="post[comments_attributes][0][relevances_attributes][0][id]" type="hidden" value="314" />' \ + '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="321" />' \ + '<input id="post_tags_attributes_0_value" name="post[tags_attributes][0][value]" type="text" value="tag #123" />' \ + '<input id="post_tags_attributes_0_relevances_attributes_0_value" name="post[tags_attributes][0][relevances_attributes][0][value]" type="text" value="tagrelevance #3141" />' \ + '<input id="post_tags_attributes_0_relevances_attributes_0_id" name="post[tags_attributes][0][relevances_attributes][0][id]" type="hidden" value="3141" />' \ + '<input id="post_tags_attributes_0_id" name="post[tags_attributes][0][id]" type="hidden" value="123" />' \ + '<input id="post_tags_attributes_1_value" name="post[tags_attributes][1][value]" type="text" value="tag #456" />' \ + '<input id="post_tags_attributes_1_relevances_attributes_0_value" name="post[tags_attributes][1][relevances_attributes][0][value]" type="text" value="tagrelevance #31415" />' \ + '<input id="post_tags_attributes_1_relevances_attributes_0_id" name="post[tags_attributes][1][relevances_attributes][0][id]" type="hidden" value="31415" />' \ '<input id="post_tags_attributes_1_id" name="post[tags_attributes][1][id]" type="hidden" value="456" />' end @@ -3075,7 +3056,7 @@ class FormHelperTest < ActionView::TestCase } end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do '<input id="post_author_attributes_name" name="post[author_attributes][name]" type="text" value="hash backed author" />' end @@ -3090,9 +3071,9 @@ class FormHelperTest < ActionView::TestCase end expected = - "<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[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' />" assert_dom_equal expected, output_buffer @@ -3106,9 +3087,9 @@ class FormHelperTest < ActionView::TestCase end expected = - "<input name='post[123][title]' type='text' id='post_123_title' value='Hello World' />" + - "<textarea name='post[123][body]' id='post_123_body'>\nBack to the hill and over it again!</textarea>" + - "<input name='post[123][secret]' type='hidden' value='0' />" + + "<input name='post[123][title]' type='text' id='post_123_title' value='Hello World' />" \ + "<textarea name='post[123][body]' id='post_123_body'>\nBack to the hill and over it again!</textarea>" \ + "<input name='post[123][secret]' type='hidden' value='0' />" \ "<input name='post[123][secret]' checked='checked' type='checkbox' id='post_123_secret' value='1' />" assert_dom_equal expected, output_buffer @@ -3122,9 +3103,9 @@ class FormHelperTest < ActionView::TestCase end expected = - "<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[][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' />" assert_dom_equal expected, output_buffer @@ -3138,9 +3119,9 @@ class FormHelperTest < ActionView::TestCase end expected = - "<input name='post[abc][title]' type='text' id='post_abc_title' value='Hello World' />" + - "<textarea name='post[abc][body]' id='post_abc_body'>\nBack to the hill and over it again!</textarea>" + - "<input name='post[abc][secret]' type='hidden' value='0' />" + + "<input name='post[abc][title]' type='text' id='post_abc_title' value='Hello World' />" \ + "<textarea name='post[abc][body]' id='post_abc_body'>\nBack to the hill and over it again!</textarea>" \ + "<input name='post[abc][secret]' type='hidden' value='0' />" \ "<input name='post[abc][secret]' checked='checked' type='checkbox' id='post_abc_secret' value='1' />" assert_dom_equal expected, output_buffer @@ -3154,9 +3135,9 @@ class FormHelperTest < ActionView::TestCase end expected = - "<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[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' />" assert_dom_equal expected, output_buffer @@ -3170,9 +3151,9 @@ class FormHelperTest < ActionView::TestCase end expected = - "<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[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' />" assert_dom_equal expected, output_buffer @@ -3184,7 +3165,7 @@ class FormHelperTest < ActionView::TestCase concat f.text_field(:title) end - assert_dom_equal "<label for=\"author_post_title\">Title</label>" + + assert_dom_equal "<label for=\"author_post_title\">Title</label>" \ "<input name='author[post][title]' type='text' id='author_post_title' value='Hello World' />", output_buffer end @@ -3195,17 +3176,17 @@ class FormHelperTest < ActionView::TestCase concat f.text_field(:title) end - assert_dom_equal "<label for=\"author_post_1_title\">Title</label>" + + assert_dom_equal "<label for=\"author_post_1_title\">Title</label>" \ "<input name='author[post][1][title]' type='text' id='author_post_1_title' value='Hello World' />", output_buffer end def test_form_builder_does_not_have_form_for_method - assert !ActionView::Helpers::FormBuilder.instance_methods.include?(:form_for) + assert_not_includes ActionView::Helpers::FormBuilder.instance_methods, :form_for end def test_form_for_and_fields_for - form_for(@post, as: :post, html: { id: 'create-post' }) do |post_form| + form_for(@post, as: :post, html: { id: "create-post" }) do |post_form| concat post_form.text_field(:title) concat post_form.text_area(:body) @@ -3214,10 +3195,10 @@ class FormHelperTest < ActionView::TestCase } end - expected = whole_form('/posts/123', 'create-post', 'edit_post', method: 'patch') 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='parent_post[secret]' type='hidden' value='0' />" + + expected = whole_form("/posts/123", "create-post", "edit_post", method: "patch") 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='parent_post[secret]' type='hidden' value='0' />" \ "<input name='parent_post[secret]' checked='checked' type='checkbox' id='parent_post_secret' value='1' />" end @@ -3225,7 +3206,7 @@ class FormHelperTest < ActionView::TestCase end def test_form_for_and_fields_for_with_object - form_for(@post, as: :post, html: { id: 'create-post' }) do |post_form| + form_for(@post, as: :post, html: { id: "create-post" }) do |post_form| concat post_form.text_field(:title) concat post_form.text_area(:body) @@ -3234,9 +3215,9 @@ class FormHelperTest < ActionView::TestCase } end - expected = whole_form('/posts/123', 'create-post', 'edit_post', method: 'patch') 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>" + + expected = whole_form("/posts/123", "create-post", "edit_post", method: "patch") 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[comment][name]' type='text' id='post_comment_name' value='new comment' />" end @@ -3250,7 +3231,7 @@ class FormHelperTest < ActionView::TestCase } end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do "<input name='post[category][name]' type='text' id='post_category_name' />" end @@ -3274,9 +3255,9 @@ class FormHelperTest < ActionView::TestCase concat f.check_box(:secret) end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - "<label for='title'>Title:</label> <input name='post[title]' type='text' id='post_title' value='Hello World' /><br/>" + - "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea><br/>" + + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + "<label for='title'>Title:</label> <input name='post[title]' type='text' id='post_title' value='Hello World' /><br/>" \ + "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea><br/>" \ "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>" end @@ -3293,9 +3274,9 @@ class FormHelperTest < ActionView::TestCase concat f.check_box(:secret) end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do - "<label for='title'>Title:</label> <input name='post[title]' type='text' id='post_title' value='Hello World' /><br/>" + - "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea><br/>" + + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + "<label for='title'>Title:</label> <input name='post[title]' type='text' id='post_title' value='Hello World' /><br/>" \ + "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea><br/>" \ "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>" end @@ -3312,7 +3293,7 @@ class FormHelperTest < ActionView::TestCase concat f.text_field(:title) end - expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do "<label for='title'>Title:</label> <input name='post[title]' type='text' id='post_title' value='Hello World' /><br/>" end @@ -3353,8 +3334,8 @@ class FormHelperTest < ActionView::TestCase end expected = - "<label for='title'>Title:</label> <input name='post[title]' type='text' id='post_title' value='Hello World' /><br/>" + - "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea><br/>" + + "<label for='title'>Title:</label> <input name='post[title]' type='text' id='post_title' value='Hello World' /><br/>" \ + "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body'>\nBack to the hill and over it again!</textarea><br/>" \ "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>" assert_dom_equal expected, output_buffer @@ -3366,7 +3347,7 @@ class FormHelperTest < ActionView::TestCase form_for(@post, builder: LabelledFormBuilder) do |f| f.fields_for(:comments, Comment.new) do |nested_fields| klass = nested_fields.class - '' + "" end end @@ -3377,9 +3358,9 @@ class FormHelperTest < ActionView::TestCase klass = nil form_for(@post, builder: LabelledFormBuilder) do |f| - f.fields_for(:comments, Comment.new, index: 'foo') do |nested_fields| + f.fields_for(:comments, Comment.new, index: "foo") do |nested_fields| klass = nested_fields.class - '' + "" end end @@ -3391,10 +3372,10 @@ class FormHelperTest < ActionView::TestCase form_for(@post, builder: LabelledFormBuilder) do |f| path = f.to_partial_path - '' + "" end - assert_equal 'labelled_form', path + assert_equal "labelled_form", path end class LabelledFormBuilderSubclass < LabelledFormBuilder; end @@ -3405,7 +3386,7 @@ class FormHelperTest < ActionView::TestCase form_for(@post, builder: LabelledFormBuilder) do |f| f.fields_for(:comments, Comment.new, builder: LabelledFormBuilderSubclass) do |nested_fields| klass = nested_fields.class - '' + "" end end @@ -3413,23 +3394,23 @@ class FormHelperTest < ActionView::TestCase end def test_form_for_with_html_options_adds_options_to_form_tag - form_for(@post, html: { id: 'some_form', class: 'some_class', multipart: true }) do |f| end + form_for(@post, html: { id: "some_form", class: "some_class", multipart: true }) do |f| end expected = whole_form("/posts/123", "some_form", "some_class", method: "patch", multipart: "multipart/form-data") assert_dom_equal expected, output_buffer end def test_form_for_with_string_url_option - form_for(@post, url: 'http://www.otherdomain.com') do |f| end + form_for(@post, url: "http://www.otherdomain.com") do |f| end assert_dom_equal whole_form("http://www.otherdomain.com", "edit_post_123", "edit_post", method: "patch"), output_buffer end def test_form_for_with_hash_url_option - form_for(@post, url: { controller: 'controller', action: 'action' }) do |f| end + form_for(@post, url: { controller: "controller", action: "action" }) do |f| end - assert_equal 'controller', @url_for_options[:controller] - assert_equal 'action', @url_for_options[:action] + assert_equal "controller", @url_for_options[:controller] + assert_equal "action", @url_for_options[:action] end def test_form_for_with_record_url_option @@ -3520,54 +3501,54 @@ class FormHelperTest < ActionView::TestCase end end - form_for(@post, builder: builder_class) { } - assert_equal 1, initialization_count, 'form builder instantiated more than once' + form_for(@post, builder: builder_class) {} + assert_equal 1, initialization_count, "form builder instantiated more than once" end - protected + private - def hidden_fields(options = {}) - method = options[:method] + def hidden_fields(options = {}) + method = options[:method] - if options.fetch(:enforce_utf8, true) - txt = %{<input name="utf8" type="hidden" value="✓" />} - else - txt = '' - end + if options.fetch(:enforce_utf8, true) + txt = %{<input name="utf8" type="hidden" value="✓" />}.dup + else + txt = "".dup + end - if method && !%w(get post).include?(method.to_s) - txt << %{<input name="_method" type="hidden" value="#{method}" />} - end + if method && !%w(get post).include?(method.to_s) + txt << %{<input name="_method" type="hidden" value="#{method}" />} + end - txt - end + txt + end - def form_text(action = "/", id = nil, html_class = nil, remote = nil, multipart = nil, method = nil) - txt = %{<form accept-charset="UTF-8" action="#{action}"} - txt << %{ enctype="multipart/form-data"} if multipart - txt << %{ data-remote="true"} if remote - txt << %{ class="#{html_class}"} if html_class - txt << %{ id="#{id}"} if id - method = method.to_s == "get" ? "get" : "post" - txt << %{ method="#{method}">} - end + def form_text(action = "/", id = nil, html_class = nil, remote = nil, multipart = nil, method = nil) + txt = %{<form accept-charset="UTF-8" action="#{action}"}.dup + txt << %{ enctype="multipart/form-data"} if multipart + txt << %{ data-remote="true"} if remote + txt << %{ class="#{html_class}"} if html_class + txt << %{ id="#{id}"} if id + method = method.to_s == "get" ? "get" : "post" + txt << %{ method="#{method}">} + end - def whole_form(action = "/", id = nil, html_class = nil, options = {}) - contents = block_given? ? yield : "" + def whole_form(action = "/", id = nil, html_class = nil, options = {}) + contents = block_given? ? yield : "" - method, remote, multipart = options.values_at(:method, :remote, :multipart) + method, remote, multipart = options.values_at(:method, :remote, :multipart) - form_text(action, id, html_class, remote, multipart, method) + hidden_fields(options.slice :method, :enforce_utf8) + contents + "</form>" - end + form_text(action, id, html_class, remote, multipart, method) + hidden_fields(options.slice :method, :enforce_utf8) + contents + "</form>" + end - def protect_against_forgery? - false - end + def protect_against_forgery? + false + end - def with_locale(testing_locale = :label) - old_locale, I18n.locale = I18n.locale, testing_locale - yield - ensure - I18n.locale = old_locale - end + def with_locale(testing_locale = :label) + old_locale, I18n.locale = I18n.locale, testing_locale + yield + ensure + I18n.locale = old_locale + end end diff --git a/actionview/test/template/form_options_helper_i18n_test.rb b/actionview/test/template/form_options_helper_i18n_test.rb index 26ede09a5f..21295fa547 100644 --- a/actionview/test/template/form_options_helper_i18n_test.rb +++ b/actionview/test/template/form_options_helper_i18n_test.rb @@ -1,12 +1,14 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class FormOptionsHelperI18nTests < ActionView::TestCase tests ActionView::Helpers::FormOptionsHelper def setup - @prompt_message = 'Select!' + @prompt_message = "Select!" I18n.backend.send(:init_translations) - I18n.backend.store_translations :en, :helpers => { :select => { :prompt => @prompt_message } } + I18n.backend.store_translations :en, helpers: { select: { prompt: @prompt_message } } end def teardown @@ -14,15 +16,15 @@ class FormOptionsHelperI18nTests < ActionView::TestCase end def test_select_with_prompt_true_translates_prompt_message - assert_called_with(I18n, :translate, ['helpers.select.prompt', { :default => 'Please select' }]) do - 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 assert_dom_equal( %Q(<select id="post_category" name="post[category]"><option value="">#{@prompt_message}</option>\n</select>), - select('post', 'category', [], :prompt => true) + select("post", "category", [], prompt: true) ) end end diff --git a/actionview/test/template/form_options_helper_test.rb b/actionview/test/template/form_options_helper_test.rb index c5b63d33f1..642f450f91 100644 --- a/actionview/test/template/form_options_helper_test.rb +++ b/actionview/test/template/form_options_helper_test.rb @@ -1,4 +1,6 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class Map < Hash def category @@ -6,15 +8,24 @@ class Map < Hash end end +class CustomEnumerable + include Enumerable + + def each + yield "one" + yield "two" + end +end + class FormOptionsHelperTest < ActionView::TestCase tests ActionView::Helpers::FormOptionsHelper silence_warnings do - Post = Struct.new('Post', :title, :author_name, :body, :secret, :written_on, :category, :origin, :allow_comments) - Continent = Struct.new('Continent', :continent_name, :countries) - Country = Struct.new('Country', :country_id, :country_name) - Firm = Struct.new('Firm', :time_zone) - Album = Struct.new('Album', :id, :title, :genre) + Post = Struct.new("Post", :title, :author_name, :body, :secret, :written_on, :category, :origin, :allow_comments) + Continent = Struct.new("Continent", :continent_name, :countries) + Country = Struct.new("Country", :country_id, :country_name) + Firm = Struct.new("Firm", :time_zone) + Album = Struct.new("Album", :id, :title, :genre) end module FakeZones @@ -57,7 +68,6 @@ class FormOptionsHelperTest < ActionView::TestCase ) end - def test_collection_options_with_preselected_value assert_dom_equal( "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" selected=\"selected\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>", @@ -66,44 +76,44 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_collection_options_with_preselected_value_array - assert_dom_equal( - "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" selected=\"selected\">Babe went home</option>\n<option value=\"Cabe\" selected=\"selected\">Cabe went home</option>", - options_from_collection_for_select(dummy_posts, "author_name", "title", [ "Babe", "Cabe" ]) - ) + assert_dom_equal( + "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" selected=\"selected\">Babe went home</option>\n<option value=\"Cabe\" selected=\"selected\">Cabe went home</option>", + options_from_collection_for_select(dummy_posts, "author_name", "title", [ "Babe", "Cabe" ]) + ) end def test_collection_options_with_proc_for_selected assert_dom_equal( "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" selected=\"selected\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>", - options_from_collection_for_select(dummy_posts, "author_name", "title", lambda{|p| p.author_name == 'Babe' }) + options_from_collection_for_select(dummy_posts, "author_name", "title", lambda { |p| p.author_name == "Babe" }) ) end def test_collection_options_with_disabled_value assert_dom_equal( "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" disabled=\"disabled\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>", - options_from_collection_for_select(dummy_posts, "author_name", "title", :disabled => "Babe") + options_from_collection_for_select(dummy_posts, "author_name", "title", disabled: "Babe") ) end def test_collection_options_with_disabled_array assert_dom_equal( "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" disabled=\"disabled\">Babe went home</option>\n<option value=\"Cabe\" disabled=\"disabled\">Cabe went home</option>", - options_from_collection_for_select(dummy_posts, "author_name", "title", :disabled => [ "Babe", "Cabe" ]) + options_from_collection_for_select(dummy_posts, "author_name", "title", disabled: [ "Babe", "Cabe" ]) ) end def test_collection_options_with_preselected_and_disabled_value assert_dom_equal( "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" disabled=\"disabled\">Babe went home</option>\n<option value=\"Cabe\" selected=\"selected\">Cabe went home</option>", - options_from_collection_for_select(dummy_posts, "author_name", "title", :selected => "Cabe", :disabled => "Babe") + options_from_collection_for_select(dummy_posts, "author_name", "title", selected: "Cabe", disabled: "Babe") ) end def test_collection_options_with_proc_for_disabled assert_dom_equal( "<option value=\"<Abe>\"><Abe> went home</option>\n<option value=\"Babe\" disabled=\"disabled\">Babe went home</option>\n<option value=\"Cabe\" disabled=\"disabled\">Cabe went home</option>", - options_from_collection_for_select(dummy_posts, "author_name", "title", :disabled => lambda {|p| %w(Babe Cabe).include?(p.author_name)}) + options_from_collection_for_select(dummy_posts, "author_name", "title", disabled: lambda { |p| %w(Babe Cabe).include?(p.author_name) }) ) end @@ -124,7 +134,7 @@ class FormOptionsHelperTest < ActionView::TestCase def test_collection_options_with_element_attributes assert_dom_equal( "<option value=\"USA\" class=\"bold\">USA</option>", - options_from_collection_for_select([[ "USA", "USA", { :class => 'bold' } ]], :first, :second) + options_from_collection_for_select([[ "USA", "USA", { class: "bold" } ]], :first, :second) ) end @@ -147,8 +157,8 @@ class FormOptionsHelperTest < ActionView::TestCase assert_dom_equal( "<option selected=\"selected\" type=\"Coach\" value=\"1\">Richard Bandler</option>\n<option type=\"Coachee\" value=\"1\">Richard Bandler</option>", options_for_select([ - ['Richard Bandler', 1, { type: 'Coach', selected: 'selected' }], - ['Richard Bandler', 1, { type: 'Coachee' }] + ["Richard Bandler", 1, { type: "Coach", selected: "selected" }], + ["Richard Bandler", 1, { type: "Coachee" }] ]) ) end @@ -157,8 +167,8 @@ class FormOptionsHelperTest < ActionView::TestCase assert_dom_equal( "<option disabled=\"disabled\" type=\"Coach\" value=\"1\">Richard Bandler</option>\n<option type=\"Coachee\" value=\"1\">Richard Bandler</option>", options_for_select([ - ['Richard Bandler', 1, { type: 'Coach', disabled: 'disabled' }], - ['Richard Bandler', 1, { type: 'Coachee' }] + ["Richard Bandler", 1, { type: "Coach", disabled: "disabled" }], + ["Richard Bandler", 1, { type: "Coachee" }] ]) ) end @@ -171,37 +181,37 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_array_options_for_select_with_selection_array - assert_dom_equal( - "<option value=\"Denmark\">Denmark</option>\n<option value=\"<USA>\" selected=\"selected\"><USA></option>\n<option value=\"Sweden\" selected=\"selected\">Sweden</option>", - options_for_select([ "Denmark", "<USA>", "Sweden" ], [ "<USA>", "Sweden" ]) - ) + assert_dom_equal( + "<option value=\"Denmark\">Denmark</option>\n<option value=\"<USA>\" selected=\"selected\"><USA></option>\n<option value=\"Sweden\" selected=\"selected\">Sweden</option>", + options_for_select([ "Denmark", "<USA>", "Sweden" ], [ "<USA>", "Sweden" ]) + ) end def test_array_options_for_select_with_disabled_value assert_dom_equal( "<option value=\"Denmark\">Denmark</option>\n<option value=\"<USA>\" disabled=\"disabled\"><USA></option>\n<option value=\"Sweden\">Sweden</option>", - options_for_select([ "Denmark", "<USA>", "Sweden" ], :disabled => "<USA>") + options_for_select([ "Denmark", "<USA>", "Sweden" ], disabled: "<USA>") ) end def test_array_options_for_select_with_disabled_array assert_dom_equal( "<option value=\"Denmark\">Denmark</option>\n<option value=\"<USA>\" disabled=\"disabled\"><USA></option>\n<option value=\"Sweden\" disabled=\"disabled\">Sweden</option>", - options_for_select([ "Denmark", "<USA>", "Sweden" ], :disabled => ["<USA>", "Sweden"]) + options_for_select([ "Denmark", "<USA>", "Sweden" ], disabled: ["<USA>", "Sweden"]) ) end def test_array_options_for_select_with_selection_and_disabled_value assert_dom_equal( "<option value=\"Denmark\" selected=\"selected\">Denmark</option>\n<option value=\"<USA>\" disabled=\"disabled\"><USA></option>\n<option value=\"Sweden\">Sweden</option>", - options_for_select([ "Denmark", "<USA>", "Sweden" ], :selected => "Denmark", :disabled => "<USA>") + options_for_select([ "Denmark", "<USA>", "Sweden" ], selected: "Denmark", disabled: "<USA>") ) end def test_boolean_array_options_for_select_with_selection_and_disabled_value assert_dom_equal( "<option value=\"true\">true</option>\n<option value=\"false\" selected=\"selected\">false</option>", - options_for_select([ true, false ], :selected => false, :disabled => nil) + options_for_select([ true, false ], selected: false, disabled: nil) ) end @@ -213,18 +223,18 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_array_options_for_string_include_in_other_string_bug_fix - assert_dom_equal( - "<option value=\"ruby\">ruby</option>\n<option value=\"rubyonrails\" selected=\"selected\">rubyonrails</option>", - options_for_select([ "ruby", "rubyonrails" ], "rubyonrails") - ) - assert_dom_equal( - "<option value=\"ruby\" selected=\"selected\">ruby</option>\n<option value=\"rubyonrails\">rubyonrails</option>", - options_for_select([ "ruby", "rubyonrails" ], "ruby") - ) - assert_dom_equal( - %(<option value="ruby" selected="selected">ruby</option>\n<option value="rubyonrails">rubyonrails</option>\n<option value=""></option>), - options_for_select([ "ruby", "rubyonrails", nil ], "ruby") - ) + assert_dom_equal( + "<option value=\"ruby\">ruby</option>\n<option value=\"rubyonrails\" selected=\"selected\">rubyonrails</option>", + options_for_select([ "ruby", "rubyonrails" ], "rubyonrails") + ) + assert_dom_equal( + "<option value=\"ruby\" selected=\"selected\">ruby</option>\n<option value=\"rubyonrails\">rubyonrails</option>", + options_for_select([ "ruby", "rubyonrails" ], "ruby") + ) + assert_dom_equal( + %(<option value="ruby" selected="selected">ruby</option>\n<option value="rubyonrails">rubyonrails</option>\n<option value=""></option>), + options_for_select([ "ruby", "rubyonrails", nil ], "ruby") + ) end def test_hash_options_for_select @@ -259,64 +269,64 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_collection_options_with_preselected_value_as_string_and_option_value_is_integer - albums = [ Album.new(1, "first","rap"), Album.new(2, "second","pop")] + albums = [ Album.new(1, "first", "rap"), Album.new(2, "second", "pop")] assert_dom_equal( - %(<option selected="selected" value="1">rap</option>\n<option value="2">pop</option>), - options_from_collection_for_select(albums, "id", "genre", :selected => "1") + %(<option selected="selected" value="1">rap</option>\n<option value="2">pop</option>), + options_from_collection_for_select(albums, "id", "genre", selected: "1") ) end def test_collection_options_with_preselected_value_as_integer_and_option_value_is_string - albums = [ Album.new("1", "first","rap"), Album.new("2", "second","pop")] + albums = [ Album.new("1", "first", "rap"), Album.new("2", "second", "pop")] assert_dom_equal( - %(<option selected="selected" value="1">rap</option>\n<option value="2">pop</option>), - options_from_collection_for_select(albums, "id", "genre", :selected => 1) + %(<option selected="selected" value="1">rap</option>\n<option value="2">pop</option>), + options_from_collection_for_select(albums, "id", "genre", selected: 1) ) end def test_collection_options_with_preselected_value_as_string_and_option_value_is_float - albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")] + albums = [ Album.new(1.0, "first", "rap"), Album.new(2.0, "second", "pop")] assert_dom_equal( - %(<option value="1.0">rap</option>\n<option value="2.0" selected="selected">pop</option>), - options_from_collection_for_select(albums, "id", "genre", :selected => "2.0") + %(<option value="1.0">rap</option>\n<option value="2.0" selected="selected">pop</option>), + options_from_collection_for_select(albums, "id", "genre", selected: "2.0") ) end def test_collection_options_with_preselected_value_as_nil - albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")] + albums = [ Album.new(1.0, "first", "rap"), Album.new(2.0, "second", "pop")] assert_dom_equal( - %(<option value="1.0">rap</option>\n<option value="2.0">pop</option>), - options_from_collection_for_select(albums, "id", "genre", :selected => nil) + %(<option value="1.0">rap</option>\n<option value="2.0">pop</option>), + options_from_collection_for_select(albums, "id", "genre", selected: nil) ) end def test_collection_options_with_disabled_value_as_nil - albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")] + albums = [ Album.new(1.0, "first", "rap"), Album.new(2.0, "second", "pop")] assert_dom_equal( - %(<option value="1.0">rap</option>\n<option value="2.0">pop</option>), - options_from_collection_for_select(albums, "id", "genre", :disabled => nil) + %(<option value="1.0">rap</option>\n<option value="2.0">pop</option>), + options_from_collection_for_select(albums, "id", "genre", disabled: nil) ) end def test_collection_options_with_disabled_value_as_array - albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop")] + albums = [ Album.new(1.0, "first", "rap"), Album.new(2.0, "second", "pop")] assert_dom_equal( - %(<option disabled="disabled" value="1.0">rap</option>\n<option disabled="disabled" value="2.0">pop</option>), - options_from_collection_for_select(albums, "id", "genre", :disabled => ["1.0", 2.0]) + %(<option disabled="disabled" value="1.0">rap</option>\n<option disabled="disabled" value="2.0">pop</option>), + options_from_collection_for_select(albums, "id", "genre", disabled: ["1.0", 2.0]) ) end def test_collection_options_with_preselected_values_as_string_array_and_option_value_is_float - albums = [ Album.new(1.0, "first","rap"), Album.new(2.0, "second","pop"), Album.new(3.0, "third","country") ] + albums = [ Album.new(1.0, "first", "rap"), Album.new(2.0, "second", "pop"), Album.new(3.0, "third", "country") ] assert_dom_equal( - %(<option value="1.0" selected="selected">rap</option>\n<option value="2.0">pop</option>\n<option value="3.0" selected="selected">country</option>), - options_from_collection_for_select(albums, "id", "genre", ["1.0","3.0"]) + %(<option value="1.0" selected="selected">rap</option>\n<option value="2.0">pop</option>\n<option value="3.0" selected="selected">country</option>), + options_from_collection_for_select(albums, "id", "genre", ["1.0", "3.0"]) ) end @@ -327,6 +337,22 @@ class FormOptionsHelperTest < ActionView::TestCase ) end + def test_option_groups_from_collection_for_select_with_callable_group_method + group_proc = Proc.new { |c| c.countries } + assert_dom_equal( + "<optgroup label=\"<Africa>\"><option value=\"<sa>\"><South Africa></option>\n<option value=\"so\">Somalia</option></optgroup><optgroup label=\"Europe\"><option value=\"dk\" selected=\"selected\">Denmark</option>\n<option value=\"ie\">Ireland</option></optgroup>", + option_groups_from_collection_for_select(dummy_continents, group_proc, "continent_name", "country_id", "country_name", "dk") + ) + end + + def test_option_groups_from_collection_for_select_with_callable_group_label_method + label_proc = Proc.new { |c| c.continent_name } + assert_dom_equal( + "<optgroup label=\"<Africa>\"><option value=\"<sa>\"><South Africa></option>\n<option value=\"so\">Somalia</option></optgroup><optgroup label=\"Europe\"><option value=\"dk\" selected=\"selected\">Denmark</option>\n<option value=\"ie\">Ireland</option></optgroup>", + option_groups_from_collection_for_select(dummy_continents, "countries", label_proc, "country_id", "country_name", "dk") + ) + end + def test_option_groups_from_collection_for_select_returns_html_safe_string assert option_groups_from_collection_for_select(dummy_continents, "countries", "continent_name", "country_id", "country_name", "dk").html_safe? end @@ -336,9 +362,9 @@ class FormOptionsHelperTest < ActionView::TestCase "<optgroup label=\"North America\"><option value=\"US\">United States</option>\n<option value=\"Canada\">Canada</option></optgroup><optgroup label=\"Europe\"><option value=\"GB\">Great Britain</option>\n<option value=\"Germany\">Germany</option></optgroup>", grouped_options_for_select([ ["North America", - [['United States','US'],"Canada"]], + [["United States", "US"], "Canada"]], ["Europe", - [["Great Britain","GB"], "Germany"]] + [["Great Britain", "GB"], "Germany"]] ]) ) end @@ -347,8 +373,8 @@ class FormOptionsHelperTest < ActionView::TestCase assert_dom_equal( "<optgroup label=\"North America\" data-foo=\"bar\"><option value=\"US\">United States</option>\n<option value=\"Canada\">Canada</option></optgroup><optgroup label=\"Europe\" disabled=\"disabled\"><option value=\"GB\">Great Britain</option>\n<option value=\"Germany\">Germany</option></optgroup>", grouped_options_for_select([ - ["North America", [['United States','US'],"Canada"], :data => { :foo => 'bar' }], - ["Europe", [["Great Britain","GB"], "Germany"], :disabled => 'disabled'] + ["North America", [["United States", "US"], "Canada"], data: { foo: "bar" }], + ["Europe", [["Great Britain", "GB"], "Germany"], disabled: "disabled"] ]) ) end @@ -357,110 +383,110 @@ class FormOptionsHelperTest < ActionView::TestCase assert_dom_equal( "<optgroup label=\"----------\"><option value=\"US\">US</option>\n<option value=\"Canada\">Canada</option></optgroup><optgroup label=\"----------\"><option value=\"GB\">GB</option>\n<option value=\"Germany\">Germany</option></optgroup>", - grouped_options_for_select([['US',"Canada"] , ["GB", "Germany"]], nil, divider: "----------") + grouped_options_for_select([["US", "Canada"], ["GB", "Germany"]], nil, divider: "----------") ) end def test_grouped_options_for_select_with_selected_and_prompt assert_dom_equal( - "<option value=\"\">Choose a product...</option><optgroup label=\"Hats\"><option value=\"Baseball Cap\">Baseball Cap</option>\n<option selected=\"selected\" value=\"Cowboy Hat\">Cowboy Hat</option></optgroup>", - grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]], "Cowboy Hat", prompt: "Choose a product...") + "<option value=\"\">Choose a product...</option><optgroup label=\"Hats\"><option value=\"Baseball Cap\">Baseball Cap</option>\n<option selected=\"selected\" value=\"Cowboy Hat\">Cowboy Hat</option></optgroup>", + grouped_options_for_select([["Hats", ["Baseball Cap", "Cowboy Hat"]]], "Cowboy Hat", prompt: "Choose a product...") ) end def test_grouped_options_for_select_with_selected_and_prompt_true assert_dom_equal( - "<option value=\"\">Please select</option><optgroup label=\"Hats\"><option value=\"Baseball Cap\">Baseball Cap</option>\n<option selected=\"selected\" value=\"Cowboy Hat\">Cowboy Hat</option></optgroup>", - grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]], "Cowboy Hat", prompt: true) + "<option value=\"\">Please select</option><optgroup label=\"Hats\"><option value=\"Baseball Cap\">Baseball Cap</option>\n<option selected=\"selected\" value=\"Cowboy Hat\">Cowboy Hat</option></optgroup>", + grouped_options_for_select([["Hats", ["Baseball Cap", "Cowboy Hat"]]], "Cowboy Hat", prompt: true) ) end def test_grouped_options_for_select_returns_html_safe_string - assert grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]]).html_safe? + assert grouped_options_for_select([["Hats", ["Baseball Cap", "Cowboy Hat"]]]).html_safe? end def test_grouped_options_for_select_with_prompt_returns_html_escaped_string assert_dom_equal( "<option value=\"\"><Choose One></option><optgroup label=\"Hats\"><option value=\"Baseball Cap\">Baseball Cap</option>\n<option value=\"Cowboy Hat\">Cowboy Hat</option></optgroup>", - grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]], nil, prompt: '<Choose One>')) + grouped_options_for_select([["Hats", ["Baseball Cap", "Cowboy Hat"]]], nil, prompt: "<Choose One>")) end def test_optgroups_with_with_options_with_hash assert_dom_equal( - "<optgroup label=\"North America\"><option value=\"United States\">United States</option>\n<option value=\"Canada\">Canada</option></optgroup><optgroup label=\"Europe\"><option value=\"Denmark\">Denmark</option>\n<option value=\"Germany\">Germany</option></optgroup>", - grouped_options_for_select({'North America' => ['United States','Canada'], 'Europe' => ['Denmark','Germany']}) + "<optgroup label=\"North America\"><option value=\"United States\">United States</option>\n<option value=\"Canada\">Canada</option></optgroup><optgroup label=\"Europe\"><option value=\"Denmark\">Denmark</option>\n<option value=\"Germany\">Germany</option></optgroup>", + grouped_options_for_select("North America" => ["United States", "Canada"], "Europe" => ["Denmark", "Germany"]) ) end def test_time_zone_options_no_params opts = time_zone_options_for_select - assert_dom_equal "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\">D</option>\n" + + assert_dom_equal "<option value=\"A\">A</option>\n" \ + "<option value=\"B\">B</option>\n" \ + "<option value=\"C\">C</option>\n" \ + "<option value=\"D\">D</option>\n" \ "<option value=\"E\">E</option>", opts end def test_time_zone_options_with_selected - opts = time_zone_options_for_select( "D" ) - assert_dom_equal "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>\n" + + opts = time_zone_options_for_select("D") + assert_dom_equal "<option value=\"A\">A</option>\n" \ + "<option value=\"B\">B</option>\n" \ + "<option value=\"C\">C</option>\n" \ + "<option value=\"D\" selected=\"selected\">D</option>\n" \ "<option value=\"E\">E</option>", opts end def test_time_zone_options_with_unknown_selected - opts = time_zone_options_for_select( "K" ) - assert_dom_equal "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\">D</option>\n" + + opts = time_zone_options_for_select("K") + assert_dom_equal "<option value=\"A\">A</option>\n" \ + "<option value=\"B\">B</option>\n" \ + "<option value=\"C\">C</option>\n" \ + "<option value=\"D\">D</option>\n" \ "<option value=\"E\">E</option>", opts end def test_time_zone_options_with_priority_zones - zones = [ ActiveSupport::TimeZone.new( "B" ), ActiveSupport::TimeZone.new( "E" ) ] - opts = time_zone_options_for_select( nil, zones ) - assert_dom_equal "<option value=\"B\">B</option>\n" + - "<option value=\"E\">E</option>" + - "<option value=\"\" disabled=\"disabled\">-------------</option>\n" + - "<option value=\"A\">A</option>\n" + - "<option value=\"C\">C</option>\n" + + zones = [ ActiveSupport::TimeZone.new("B"), ActiveSupport::TimeZone.new("E") ] + opts = time_zone_options_for_select(nil, zones) + assert_dom_equal "<option value=\"B\">B</option>\n" \ + "<option value=\"E\">E</option>" \ + "<option value=\"\" disabled=\"disabled\">-------------</option>\n" \ + "<option value=\"A\">A</option>\n" \ + "<option value=\"C\">C</option>\n" \ "<option value=\"D\">D</option>", opts end def test_time_zone_options_with_selected_priority_zones - zones = [ ActiveSupport::TimeZone.new( "B" ), ActiveSupport::TimeZone.new( "E" ) ] - opts = time_zone_options_for_select( "E", zones ) - assert_dom_equal "<option value=\"B\">B</option>\n" + - "<option value=\"E\" selected=\"selected\">E</option>" + - "<option value=\"\" disabled=\"disabled\">-------------</option>\n" + - "<option value=\"A\">A</option>\n" + - "<option value=\"C\">C</option>\n" + + zones = [ ActiveSupport::TimeZone.new("B"), ActiveSupport::TimeZone.new("E") ] + opts = time_zone_options_for_select("E", zones) + assert_dom_equal "<option value=\"B\">B</option>\n" \ + "<option value=\"E\" selected=\"selected\">E</option>" \ + "<option value=\"\" disabled=\"disabled\">-------------</option>\n" \ + "<option value=\"A\">A</option>\n" \ + "<option value=\"C\">C</option>\n" \ "<option value=\"D\">D</option>", opts end def test_time_zone_options_with_unselected_priority_zones - zones = [ ActiveSupport::TimeZone.new( "B" ), ActiveSupport::TimeZone.new( "E" ) ] - opts = time_zone_options_for_select( "C", zones ) - assert_dom_equal "<option value=\"B\">B</option>\n" + - "<option value=\"E\">E</option>" + - "<option value=\"\" disabled=\"disabled\">-------------</option>\n" + - "<option value=\"A\">A</option>\n" + - "<option value=\"C\" selected=\"selected\">C</option>\n" + + zones = [ ActiveSupport::TimeZone.new("B"), ActiveSupport::TimeZone.new("E") ] + opts = time_zone_options_for_select("C", zones) + assert_dom_equal "<option value=\"B\">B</option>\n" \ + "<option value=\"E\">E</option>" \ + "<option value=\"\" disabled=\"disabled\">-------------</option>\n" \ + "<option value=\"A\">A</option>\n" \ + "<option value=\"C\" selected=\"selected\">C</option>\n" \ "<option value=\"D\">D</option>", opts end def test_time_zone_options_with_priority_zones_does_not_mutate_time_zones original_zones = ActiveSupport::TimeZone.all.dup - zones = [ ActiveSupport::TimeZone.new( "B" ), ActiveSupport::TimeZone.new( "E" ) ] + zones = [ ActiveSupport::TimeZone.new("B"), ActiveSupport::TimeZone.new("E") ] time_zone_options_for_select(nil, zones) assert_equal original_zones, ActiveSupport::TimeZone.all end @@ -481,7 +507,7 @@ class FormOptionsHelperTest < ActionView::TestCase def test_select_without_multiple assert_dom_equal( "<select id=\"post_category\" name=\"post[category]\"></select>", - select(:post, :category, "", {}, :multiple => false) + select(:post, :category, "", {}, { multiple: false }) ) end @@ -495,9 +521,9 @@ class FormOptionsHelperTest < ActionView::TestCase assert_dom_equal( [ - %Q{<select id="post_origin" name="post[origin]"><optgroup label="<Africa>"><option value="<sa>"><South Africa></option>}, - %Q{<option value="so">Somalia</option></optgroup><optgroup label="Europe"><option value="dk">Denmark</option>}, - %Q{<option value="ie">Ireland</option></optgroup></select>}, + '<select id="post_origin" name="post[origin]"><optgroup label="<Africa>"><option value="<sa>"><South Africa></option>', + '<option value="so">Somalia</option></optgroup><optgroup label="Europe"><option value="dk">Denmark</option>', + '<option value="ie">Ireland</option></optgroup></select>', ].join("\n"), select("post", "origin", countries_by_continent) ) @@ -513,9 +539,9 @@ class FormOptionsHelperTest < ActionView::TestCase assert_dom_equal( [ - %Q{<select id="post_origin" name="post[origin]"><optgroup label="<Africa>"><option value="<sa>"><South Africa></option>}, - %Q{<option value="so">Somalia</option></optgroup><optgroup label="Europe"><option value="dk">Denmark</option>}, - %Q{<option value="ie">Ireland</option></optgroup></select>}, + '<select id="post_origin" name="post[origin]"><optgroup label="<Africa>"><option value="<sa>"><South Africa></option>', + '<option value="so">Somalia</option></optgroup><optgroup label="Europe"><option value="dk">Denmark</option>', + '<option value="ie">Ireland</option></optgroup></select>', ].join("\n"), select("post", "origin", countries_by_continent) ) @@ -561,7 +587,7 @@ class FormOptionsHelperTest < ActionView::TestCase @post = Post.new @post.category = "<mus>" - output_buffer = fields_for :post, @post, :index => 108 do |f| + output_buffer = fields_for :post, @post, index: 108 do |f| concat f.select(:category, %w( abe <mus> hest)) end @@ -591,7 +617,7 @@ class FormOptionsHelperTest < ActionView::TestCase options = raw("<option value=\"abe\">abe</option><option value=\"mus\">mus</option><option value=\"hest\">hest</option>") output_buffer = fields_for :post, @post do |f| - concat f.select(:category, options, :prompt => 'The prompt') + concat f.select(:category, options, prompt: "The prompt") end assert_dom_equal( @@ -629,7 +655,7 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_select_with_multiple_to_add_hidden_input - output_buffer = select(:post, :category, "", {}, :multiple => true) + output_buffer = select(:post, :category, "", {}, { multiple: true }) assert_dom_equal( "<input type=\"hidden\" name=\"post[category][]\" value=\"\"/><select multiple=\"multiple\" id=\"post_category\" name=\"post[category][]\"></select>", output_buffer @@ -637,7 +663,7 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_select_with_multiple_and_without_hidden_input - output_buffer = select(:post, :category, "", {:include_hidden => false}, :multiple => true) + output_buffer = select(:post, :category, "", { include_hidden: false }, { multiple: true }) assert_dom_equal( "<select multiple=\"multiple\" id=\"post_category\" name=\"post[category][]\"></select>", output_buffer @@ -645,7 +671,7 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_select_with_multiple_and_with_explicit_name_ending_with_brackets - output_buffer = select(:post, :category, [], {include_hidden: false}, multiple: true, name: 'post[category][]') + output_buffer = select(:post, :category, [], { include_hidden: false }, { multiple: true, name: "post[category][]" }) assert_dom_equal( "<select multiple=\"multiple\" id=\"post_category\" name=\"post[category][]\"></select>", output_buffer @@ -653,7 +679,7 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_select_with_multiple_and_disabled_to_add_disabled_hidden_input - output_buffer = select(:post, :category, "", {}, :multiple => true, :disabled => true) + output_buffer = select(:post, :category, "", {}, { multiple: true, disabled: true }) assert_dom_equal( "<input disabled=\"disabled\"type=\"hidden\" name=\"post[category][]\" value=\"\"/><select multiple=\"multiple\" disabled=\"disabled\" id=\"post_category\" name=\"post[category][]\"></select>", output_buffer @@ -665,14 +691,14 @@ class FormOptionsHelperTest < ActionView::TestCase @post.category = "<mus>" assert_dom_equal( "<select id=\"post_category\" name=\"post[category]\"><option value=\"\"></option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>", - select("post", "category", %w( abe <mus> hest), :include_blank => true) + select("post", "category", %w( abe <mus> hest), include_blank: true) ) 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') } + 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 @@ -681,7 +707,7 @@ class FormOptionsHelperTest < ActionView::TestCase @post.category = "<mus>" assert_dom_equal( "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">None</option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>", - select("post", "category", %w( abe <mus> hest), :include_blank => 'None') + select("post", "category", %w( abe <mus> hest), include_blank: "None") ) end @@ -690,7 +716,7 @@ class FormOptionsHelperTest < ActionView::TestCase @post.category = "<mus>" assert_dom_equal( "<select id=\"post_category\" name=\"post[category]\"><option value=\"\"><None></option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>", - select("post", "category", %w( abe <mus> hest), :include_blank => '<None>') + select("post", "category", %w( abe <mus> hest), include_blank: "<None>") ) end @@ -699,7 +725,7 @@ class FormOptionsHelperTest < ActionView::TestCase @post.category = "" assert_dom_equal( "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>", - select("post", "category", %w( abe <mus> hest), :prompt => true) + select("post", "category", %w( abe <mus> hest), prompt: true) ) end @@ -708,7 +734,7 @@ class FormOptionsHelperTest < ActionView::TestCase @post.category = "<mus>" assert_dom_equal( "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\">hest</option></select>", - select("post", "category", %w( abe <mus> hest), :prompt => true) + select("post", "category", %w( abe <mus> hest), prompt: true) ) end @@ -717,7 +743,7 @@ class FormOptionsHelperTest < ActionView::TestCase @post.category = "" assert_dom_equal( "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">The prompt</option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>", - select("post", "category", %w( abe <mus> hest), :prompt => 'The prompt') + select("post", "category", %w( abe <mus> hest), prompt: "The prompt") ) end @@ -725,7 +751,7 @@ class FormOptionsHelperTest < ActionView::TestCase @post = Post.new assert_dom_equal( "<select id=\"post_category\" name=\"post[category]\"><option value=\"\"><The prompt></option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>", - select("post", "category", %w( abe <mus> hest), :prompt => '<The prompt>') + select("post", "category", %w( abe <mus> hest), prompt: "<The prompt>") ) end @@ -734,16 +760,25 @@ class FormOptionsHelperTest < ActionView::TestCase @post.category = "" assert_dom_equal( "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"\"></option>\n<option value=\"abe\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>", - select("post", "category", %w( abe <mus> hest), :prompt => true, :include_blank => true) + select("post", "category", %w( abe <mus> hest), prompt: true, include_blank: true) ) end - def test_empty + def test_select_with_empty @post = Post.new @post.category = "" assert_dom_equal( "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"\"></option>\n</select>", - select("post", "category", [], :prompt => true, :include_blank => true) + select("post", "category", [], prompt: true, include_blank: true) + ) + end + + def test_select_with_html_options + @post = Post.new + @post.category = "" + assert_dom_equal( + "<select class=\"disabled\" disabled=\"disabled\" name=\"post[category]\" id=\"post_category\"><option value=\"\">Please select</option>\n<option value=\"\"></option>\n</select>", + select("post", "category", [], { prompt: true, include_blank: true }, { class: "disabled", disabled: true }) ) end @@ -759,51 +794,51 @@ class FormOptionsHelperTest < ActionView::TestCase def test_required_select assert_dom_equal( %(<select id="post_category" name="post[category]" required="required"><option value=""></option>\n<option value="abe">abe</option>\n<option value="mus">mus</option>\n<option value="hest">hest</option></select>), - select("post", "category", %w(abe mus hest), {}, required: true) + select("post", "category", %w(abe mus hest), {}, { required: true }) ) end def test_required_select_with_include_blank_prompt assert_dom_equal( %(<select id="post_category" name="post[category]" required="required"><option value="">Select one</option>\n<option value="abe">abe</option>\n<option value="mus">mus</option>\n<option value="hest">hest</option></select>), - select("post", "category", %w(abe mus hest), { include_blank: "Select one" }, required: true) + select("post", "category", %w(abe mus hest), { include_blank: "Select one" }, { required: true }) ) end def test_required_select_with_prompt assert_dom_equal( %(<select id="post_category" name="post[category]" required="required"><option value="">Select one</option>\n<option value="abe">abe</option>\n<option value="mus">mus</option>\n<option value="hest">hest</option></select>), - select("post", "category", %w(abe mus hest), { prompt: "Select one" }, required: true) + select("post", "category", %w(abe mus hest), { prompt: "Select one" }, { required: true }) ) end def test_required_select_display_size_equals_to_one assert_dom_equal( %(<select id="post_category" name="post[category]" required="required" size="1"><option value=""></option>\n<option value="abe">abe</option>\n<option value="mus">mus</option>\n<option value="hest">hest</option></select>), - select("post", "category", %w(abe mus hest), {}, required: true, size: 1) + select("post", "category", %w(abe mus hest), {}, { required: true, size: 1 }) ) end def test_required_select_with_display_size_bigger_than_one assert_dom_equal( %(<select id="post_category" name="post[category]" required="required" size="2"><option value="abe">abe</option>\n<option value="mus">mus</option>\n<option value="hest">hest</option></select>), - select("post", "category", %w(abe mus hest), {}, required: true, size: 2) + select("post", "category", %w(abe mus hest), {}, { required: true, size: 2 }) ) end def test_required_select_with_multiple_option assert_dom_equal( %(<input name="post[category][]" type="hidden" value=""/><select id="post_category" multiple="multiple" name="post[category][]" required="required"><option value="abe">abe</option>\n<option value="mus">mus</option>\n<option value="hest">hest</option></select>), - select("post", "category", %w(abe mus hest), {}, required: true, multiple: true) + select("post", "category", %w(abe mus hest), {}, { required: true, multiple: true }) ) end - def test_select_with_fixnum + def test_select_with_integer @post = Post.new @post.category = "" assert_dom_equal( "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"\"></option>\n<option value=\"1\">1</option></select>", - select("post", "category", [1], :prompt => true, :include_blank => true) + select("post", "category", [1], prompt: true, include_blank: true) ) end @@ -812,7 +847,7 @@ class FormOptionsHelperTest < ActionView::TestCase @post.category = "" assert_dom_equal( "<select id=\"post_category\" name=\"post[category]\"><option value=\"\">Please select</option>\n<option value=\"\"></option>\n<option value=\"number\">Number</option>\n<option value=\"text\">Text</option>\n<option value=\"boolean\">Yes/No</option></select>", - select("post", "category", [["Number", "number"], ["Text", "text"], ["Yes/No", "boolean"]], :prompt => true, :include_blank => true) + select("post", "category", [["Number", "number"], ["Text", "text"], ["Yes/No", "boolean"]], prompt: true, include_blank: true) ) end @@ -821,7 +856,7 @@ class FormOptionsHelperTest < ActionView::TestCase @post.category = "<mus>" assert_dom_equal( "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\" selected=\"selected\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>", - select("post", "category", %w( abe <mus> hest ), :selected => 'abe') + select("post", "category", %w( abe <mus> hest ), selected: "abe") ) end @@ -833,14 +868,14 @@ class FormOptionsHelperTest < ActionView::TestCase assert_dom_equal( expected, - select("album[]", "genre", %w[rap rock country], {}, { :index => nil }) + select("album[]", "genre", %w[rap rock country], {}, { index: nil }) ) end def test_select_escapes_options assert_dom_equal( '<select id="post_title" name="post[title]"><script>alert(1)</script></select>', - select('post', 'title', '<script>alert(1)</script>') + select("post", "title", "<script>alert(1)</script>") ) end @@ -849,7 +884,7 @@ class FormOptionsHelperTest < ActionView::TestCase @post.category = "<mus>" assert_dom_equal( "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\"><mus></option>\n<option value=\"hest\">hest</option></select>", - select("post", "category", %w( abe <mus> hest ), :selected => nil) + select("post", "category", %w( abe <mus> hest ), selected: nil) ) end @@ -858,7 +893,7 @@ class FormOptionsHelperTest < ActionView::TestCase @post.category = "<mus>" assert_dom_equal( "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\" disabled=\"disabled\">hest</option></select>", - select("post", "category", %w( abe <mus> hest ), :disabled => 'hest') + select("post", "category", %w( abe <mus> hest ), disabled: "hest") ) end @@ -866,7 +901,7 @@ class FormOptionsHelperTest < ActionView::TestCase @post = Post.new assert_dom_equal( "<select id=\"post_locale\" name=\"post[locale]\"><option value=\"en\">en</option>\n<option value=\"ru\" selected=\"selected\">ru</option></select>", - select("post", "locale", %w( en ru ), :selected => 'ru') + select("post", "locale", %w( en ru ), selected: "ru") ) end @@ -874,7 +909,7 @@ class FormOptionsHelperTest < ActionView::TestCase @post = Post.new assert_dom_equal( "<select id=\"post_category\" name=\"post[category]\"><option value=\"one\">one</option>\n<option selected=\"selected\" value=\"two\">two</option></select>", - select("post", "category", %w( one two ), :selected => 'two', :prompt => true) + select("post", "category", %w( one two ), selected: "two", prompt: true) ) end @@ -883,7 +918,7 @@ class FormOptionsHelperTest < ActionView::TestCase @post.category = "<mus>" assert_dom_equal( "<select id=\"post_category\" name=\"post[category]\"><option value=\"abe\" disabled=\"disabled\">abe</option>\n<option value=\"<mus>\" selected=\"selected\"><mus></option>\n<option value=\"hest\" disabled=\"disabled\">hest</option></select>", - select("post", "category", %w( abe <mus> hest ), :disabled => ['hest', 'abe']) + select("post", "category", %w( abe <mus> hest ), disabled: ["hest", "abe"]) ) end @@ -896,6 +931,14 @@ class FormOptionsHelperTest < ActionView::TestCase ) end + def test_select_with_enumerable + @post = Post.new + assert_dom_equal( + "<select id=\"post_category\" name=\"post[category]\"><option value=\"one\">one</option>\n<option value=\"two\">two</option></select>", + select("post", "category", CustomEnumerable.new) + ) + end + def test_collection_select @post = Post.new @post.author_name = "Babe" @@ -924,7 +967,7 @@ class FormOptionsHelperTest < ActionView::TestCase @post = Post.new @post.author_name = "Babe" - output_buffer = fields_for :post, @post, :index => 815 do |f| + output_buffer = fields_for :post, @post, index: 815 do |f| concat f.collection_select(:author_name, dummy_posts, :author_name, :author_name) end @@ -955,7 +998,7 @@ class FormOptionsHelperTest < ActionView::TestCase assert_dom_equal( "<select id=\"post_author_name\" name=\"post[author_name]\" style=\"width: 200px\"><option value=\"\"></option>\n<option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>", - collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { :include_blank => true }, "style" => "width: 200px") + collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { include_blank: true }, { "style" => "width: 200px" }) ) end @@ -965,7 +1008,7 @@ class FormOptionsHelperTest < ActionView::TestCase assert_dom_equal( "<select id=\"post_author_name\" name=\"post[author_name]\" style=\"width: 200px\"><option value=\"\">No Selection</option>\n<option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>", - collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { :include_blank => 'No Selection' }, "style" => "width: 200px") + collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { include_blank: "No Selection" }, { "style" => "width: 200px" }) ) end @@ -976,10 +1019,10 @@ class FormOptionsHelperTest < ActionView::TestCase expected = "<input type=\"hidden\" name=\"post[author_name][]\" value=\"\"/><select id=\"post_author_name\" name=\"post[author_name][]\" multiple=\"multiple\"><option value=\"\"></option>\n<option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\">Cabe</option></select>" # Should suffix default name with []. - assert_dom_equal expected, collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { :include_blank => true }, :multiple => true) + assert_dom_equal expected, collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { include_blank: true }, { multiple: true }) # Shouldn't suffix custom name with []. - assert_dom_equal expected, collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { :include_blank => true, :name => 'post[author_name][]' }, :multiple => true) + assert_dom_equal expected, collection_select("post", "author_name", dummy_posts, "author_name", "author_name", { include_blank: true, name: "post[author_name][]" }, { multiple: true }) end def test_collection_select_with_blank_and_selected @@ -988,7 +1031,7 @@ class FormOptionsHelperTest < ActionView::TestCase assert_dom_equal( %{<select id="post_author_name" name="post[author_name]"><option value=""></option>\n<option value="<Abe>" selected="selected"><Abe></option>\n<option value="Babe">Babe</option>\n<option value="Cabe">Cabe</option></select>}, - collection_select("post", "author_name", dummy_posts, "author_name", "author_name", {:include_blank => true, :selected => "<Abe>"}) + collection_select("post", "author_name", dummy_posts, "author_name", "author_name", include_blank: true, selected: "<Abe>") ) end @@ -998,7 +1041,7 @@ class FormOptionsHelperTest < ActionView::TestCase assert_dom_equal( "<select id=\"post_author_name\" name=\"post[author_name]\"><option value=\"<Abe>\"><Abe></option>\n<option value=\"Babe\" selected=\"selected\">Babe</option>\n<option value=\"Cabe\" disabled=\"disabled\">Cabe</option></select>", - collection_select("post", "author_name", dummy_posts, "author_name", "author_name", :disabled => 'Cabe') + collection_select("post", "author_name", dummy_posts, "author_name", "author_name", disabled: "Cabe") ) end @@ -1022,13 +1065,13 @@ class FormOptionsHelperTest < ActionView::TestCase def test_time_zone_select @firm = Firm.new("D") - html = time_zone_select( "firm", "time_zone" ) - assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" + - "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>\n" + - "<option value=\"E\">E</option>" + + html = time_zone_select("firm", "time_zone") + assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" \ + "<option value=\"A\">A</option>\n" \ + "<option value=\"B\">B</option>\n" \ + "<option value=\"C\">C</option>\n" \ + "<option value=\"D\" selected=\"selected\">D</option>\n" \ + "<option value=\"E\">E</option>" \ "</select>", html end @@ -1041,12 +1084,12 @@ class FormOptionsHelperTest < ActionView::TestCase end assert_dom_equal( - "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" + - "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>\n" + - "<option value=\"E\">E</option>" + + "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" \ + "<option value=\"A\">A</option>\n" \ + "<option value=\"B\">B</option>\n" \ + "<option value=\"C\">C</option>\n" \ + "<option value=\"D\" selected=\"selected\">D</option>\n" \ + "<option value=\"E\">E</option>" \ "</select>", output_buffer ) @@ -1055,17 +1098,17 @@ class FormOptionsHelperTest < ActionView::TestCase def test_time_zone_select_under_fields_for_with_index @firm = Firm.new("D") - output_buffer = fields_for :firm, @firm, :index => 305 do |f| + output_buffer = fields_for :firm, @firm, index: 305 do |f| concat f.time_zone_select(:time_zone) end assert_dom_equal( - "<select id=\"firm_305_time_zone\" name=\"firm[305][time_zone]\">" + - "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>\n" + - "<option value=\"E\">E</option>" + + "<select id=\"firm_305_time_zone\" name=\"firm[305][time_zone]\">" \ + "<option value=\"A\">A</option>\n" \ + "<option value=\"B\">B</option>\n" \ + "<option value=\"C\">C</option>\n" \ + "<option value=\"D\" selected=\"selected\">D</option>\n" \ + "<option value=\"E\">E</option>" \ "</select>", output_buffer ) @@ -1080,12 +1123,12 @@ class FormOptionsHelperTest < ActionView::TestCase end assert_dom_equal( - "<select id=\"firm_305_time_zone\" name=\"firm[305][time_zone]\">" + - "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>\n" + - "<option value=\"E\">E</option>" + + "<select id=\"firm_305_time_zone\" name=\"firm[305][time_zone]\">" \ + "<option value=\"A\">A</option>\n" \ + "<option value=\"B\">B</option>\n" \ + "<option value=\"C\">C</option>\n" \ + "<option value=\"D\" selected=\"selected\">D</option>\n" \ + "<option value=\"E\">E</option>" \ "</select>", output_buffer ) @@ -1093,28 +1136,28 @@ class FormOptionsHelperTest < ActionView::TestCase def test_time_zone_select_with_blank @firm = Firm.new("D") - html = time_zone_select("firm", "time_zone", nil, :include_blank => true) - assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" + - "<option value=\"\"></option>\n" + - "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>\n" + - "<option value=\"E\">E</option>" + + html = time_zone_select("firm", "time_zone", nil, include_blank: true) + assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" \ + "<option value=\"\"></option>\n" \ + "<option value=\"A\">A</option>\n" \ + "<option value=\"B\">B</option>\n" \ + "<option value=\"C\">C</option>\n" \ + "<option value=\"D\" selected=\"selected\">D</option>\n" \ + "<option value=\"E\">E</option>" \ "</select>", html end def test_time_zone_select_with_blank_as_string @firm = Firm.new("D") - html = time_zone_select("firm", "time_zone", nil, :include_blank => 'No Zone') - assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" + - "<option value=\"\">No Zone</option>\n" + - "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>\n" + - "<option value=\"E\">E</option>" + + html = time_zone_select("firm", "time_zone", nil, include_blank: "No Zone") + assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" \ + "<option value=\"\">No Zone</option>\n" \ + "<option value=\"A\">A</option>\n" \ + "<option value=\"B\">B</option>\n" \ + "<option value=\"C\">C</option>\n" \ + "<option value=\"D\" selected=\"selected\">D</option>\n" \ + "<option value=\"E\">E</option>" \ "</select>", html end @@ -1122,64 +1165,64 @@ class FormOptionsHelperTest < ActionView::TestCase def test_time_zone_select_with_style @firm = Firm.new("D") html = time_zone_select("firm", "time_zone", nil, {}, - "style" => "color: red") - assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\" style=\"color: red\">" + - "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>\n" + - "<option value=\"E\">E</option>" + + { "style" => "color: red" }) + assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\" style=\"color: red\">" \ + "<option value=\"A\">A</option>\n" \ + "<option value=\"B\">B</option>\n" \ + "<option value=\"C\">C</option>\n" \ + "<option value=\"D\" selected=\"selected\">D</option>\n" \ + "<option value=\"E\">E</option>" \ "</select>", html assert_dom_equal html, time_zone_select("firm", "time_zone", nil, {}, - :style => "color: red") + { style: "color: red" }) end def test_time_zone_select_with_blank_and_style @firm = Firm.new("D") html = time_zone_select("firm", "time_zone", nil, - { :include_blank => true }, "style" => "color: red") - assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\" style=\"color: red\">" + - "<option value=\"\"></option>\n" + - "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>\n" + - "<option value=\"E\">E</option>" + + { include_blank: true }, { "style" => "color: red" }) + assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\" style=\"color: red\">" \ + "<option value=\"\"></option>\n" \ + "<option value=\"A\">A</option>\n" \ + "<option value=\"B\">B</option>\n" \ + "<option value=\"C\">C</option>\n" \ + "<option value=\"D\" selected=\"selected\">D</option>\n" \ + "<option value=\"E\">E</option>" \ "</select>", html assert_dom_equal html, time_zone_select("firm", "time_zone", nil, - { :include_blank => true }, :style => "color: red") + { include_blank: true }, { style: "color: red" }) end def test_time_zone_select_with_blank_as_string_and_style @firm = Firm.new("D") html = time_zone_select("firm", "time_zone", nil, - { :include_blank => 'No Zone' }, "style" => "color: red") - assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\" style=\"color: red\">" + - "<option value=\"\">No Zone</option>\n" + - "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>\n" + - "<option value=\"E\">E</option>" + + { include_blank: "No Zone" }, { "style" => "color: red" }) + assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\" style=\"color: red\">" \ + "<option value=\"\">No Zone</option>\n" \ + "<option value=\"A\">A</option>\n" \ + "<option value=\"B\">B</option>\n" \ + "<option value=\"C\">C</option>\n" \ + "<option value=\"D\" selected=\"selected\">D</option>\n" \ + "<option value=\"E\">E</option>" \ "</select>", html assert_dom_equal html, time_zone_select("firm", "time_zone", nil, - { :include_blank => 'No Zone' }, :style => "color: red") + { include_blank: "No Zone" }, { style: "color: red" }) end def test_time_zone_select_with_priority_zones @firm = Firm.new("D") zones = [ ActiveSupport::TimeZone.new("A"), ActiveSupport::TimeZone.new("D") ] - html = time_zone_select("firm", "time_zone", zones ) - assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" + - "<option value=\"A\">A</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>" + - "<option value=\"\" disabled=\"disabled\">-------------</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"E\">E</option>" + + html = time_zone_select("firm", "time_zone", zones) + assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" \ + "<option value=\"A\">A</option>\n" \ + "<option value=\"D\" selected=\"selected\">D</option>" \ + "<option value=\"\" disabled=\"disabled\">-------------</option>\n" \ + "<option value=\"B\">B</option>\n" \ + "<option value=\"C\">C</option>\n" \ + "<option value=\"E\">E</option>" \ "</select>", html end @@ -1192,13 +1235,13 @@ class FormOptionsHelperTest < ActionView::TestCase end html = time_zone_select("firm", "time_zone", /A|D/) - assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" + - "<option value=\"A\">A</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>" + - "<option value=\"\" disabled=\"disabled\">-------------</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"E\">E</option>" + + assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" \ + "<option value=\"A\">A</option>\n" \ + "<option value=\"D\" selected=\"selected\">D</option>" \ + "<option value=\"\" disabled=\"disabled\">-------------</option>\n" \ + "<option value=\"B\">B</option>\n" \ + "<option value=\"C\">C</option>\n" \ + "<option value=\"E\">E</option>" \ "</select>", html end @@ -1213,42 +1256,61 @@ class FormOptionsHelperTest < ActionView::TestCase end html = time_zone_select("firm", "time_zone", /A|D/) - assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" + - "<option value=\"\" disabled=\"disabled\">-------------</option>\n" + - "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>\n" + - "<option value=\"E\">E</option>" + + assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" \ + "<option value=\"\" disabled=\"disabled\">-------------</option>\n" \ + "<option value=\"A\">A</option>\n" \ + "<option value=\"B\">B</option>\n" \ + "<option value=\"C\">C</option>\n" \ + "<option value=\"D\" selected=\"selected\">D</option>\n" \ + "<option value=\"E\">E</option>" \ "</select>", html end - def test_time_zone_select_with_default_time_zone_and_nil_value - @firm = Firm.new() - @firm.time_zone = nil + def test_time_zone_select_with_priority_zones_and_errors + @firm = Firm.new("D") + @firm.extend ActiveModel::Validations + @firm.errors[:time_zone] << "invalid" + zones = [ ActiveSupport::TimeZone.new("A"), ActiveSupport::TimeZone.new("D") ] + html = time_zone_select("firm", "time_zone", zones) + assert_dom_equal "<div class=\"field_with_errors\">" \ + "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" \ + "<option value=\"A\">A</option>\n" \ + "<option value=\"D\" selected=\"selected\">D</option>" \ + "<option value=\"\" disabled=\"disabled\">-------------</option>\n" \ + "<option value=\"B\">B</option>\n" \ + "<option value=\"C\">C</option>\n" \ + "<option value=\"E\">E</option>" \ + "</select>" \ + "</div>", + html + end - html = time_zone_select( "firm", "time_zone", nil, :default => 'B' ) - assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" + - "<option value=\"A\">A</option>\n" + - "<option value=\"B\" selected=\"selected\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\">D</option>\n" + - "<option value=\"E\">E</option>" + - "</select>", - html + def test_time_zone_select_with_default_time_zone_and_nil_value + @firm = Firm.new() + @firm.time_zone = nil + + html = time_zone_select("firm", "time_zone", nil, default: "B") + assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" \ + "<option value=\"A\">A</option>\n" \ + "<option value=\"B\" selected=\"selected\">B</option>\n" \ + "<option value=\"C\">C</option>\n" \ + "<option value=\"D\">D</option>\n" \ + "<option value=\"E\">E</option>" \ + "</select>", + html end def test_time_zone_select_with_default_time_zone_and_value - @firm = Firm.new('D') - - html = time_zone_select( "firm", "time_zone", nil, :default => 'B' ) - assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" + - "<option value=\"A\">A</option>\n" + - "<option value=\"B\">B</option>\n" + - "<option value=\"C\">C</option>\n" + - "<option value=\"D\" selected=\"selected\">D</option>\n" + - "<option value=\"E\">E</option>" + + @firm = Firm.new("D") + + html = time_zone_select("firm", "time_zone", nil, default: "B") + assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" \ + "<option value=\"A\">A</option>\n" \ + "<option value=\"B\">B</option>\n" \ + "<option value=\"C\">C</option>\n" \ + "<option value=\"D\" selected=\"selected\">D</option>\n" \ + "<option value=\"E\">E</option>" \ "</select>", html end @@ -1256,86 +1318,86 @@ class FormOptionsHelperTest < ActionView::TestCase def test_options_for_select_with_element_attributes assert_dom_equal( "<option value=\"<Denmark>\" class=\"bold\"><Denmark></option>\n<option value=\"USA\" onclick=\"alert('Hello World');\">USA</option>\n<option value=\"Sweden\">Sweden</option>\n<option value=\"Germany\">Germany</option>", - options_for_select([ [ "<Denmark>", { :class => 'bold' } ], [ "USA", { :onclick => "alert('Hello World');" } ], [ "Sweden" ], "Germany" ]) + options_for_select([ [ "<Denmark>", { class: "bold" } ], [ "USA", { onclick: "alert('Hello World');" } ], [ "Sweden" ], "Germany" ]) ) end def test_options_for_select_with_data_element assert_dom_equal( "<option value=\"<Denmark>\" data-test=\"bold\"><Denmark></option>", - options_for_select([ [ "<Denmark>", { :data => { :test => 'bold' } } ] ]) + options_for_select([ [ "<Denmark>", { data: { test: "bold" } } ] ]) ) end def test_options_for_select_with_data_element_with_special_characters assert_dom_equal( "<option value=\"<Denmark>\" data-test=\"<bold>\"><Denmark></option>", - options_for_select([ [ "<Denmark>", { :data => { :test => '<bold>' } } ] ]) + options_for_select([ [ "<Denmark>", { data: { test: "<bold>" } } ] ]) ) end def test_options_for_select_with_element_attributes_and_selection assert_dom_equal( "<option value=\"<Denmark>\"><Denmark></option>\n<option value=\"USA\" class=\"bold\" selected=\"selected\">USA</option>\n<option value=\"Sweden\">Sweden</option>", - options_for_select([ "<Denmark>", [ "USA", { :class => 'bold' } ], "Sweden" ], "USA") + options_for_select([ "<Denmark>", [ "USA", { class: "bold" } ], "Sweden" ], "USA") ) end def test_options_for_select_with_element_attributes_and_selection_array assert_dom_equal( "<option value=\"<Denmark>\"><Denmark></option>\n<option value=\"USA\" class=\"bold\" selected=\"selected\">USA</option>\n<option value=\"Sweden\" selected=\"selected\">Sweden</option>", - options_for_select([ "<Denmark>", [ "USA", { :class => 'bold' } ], "Sweden" ], [ "USA", "Sweden" ]) + options_for_select([ "<Denmark>", [ "USA", { class: "bold" } ], "Sweden" ], [ "USA", "Sweden" ]) ) end def test_options_for_select_with_special_characters assert_dom_equal( "<option value=\"<Denmark>\" onclick=\"alert("<code>")\"><Denmark></option>", - options_for_select([ [ "<Denmark>", { :onclick => %(alert("<code>")) } ] ]) + options_for_select([ [ "<Denmark>", { onclick: %(alert("<code>")) } ] ]) ) end def test_option_html_attributes_with_no_array_element - assert_equal({}, option_html_attributes('foo')) + assert_equal({}, option_html_attributes("foo")) end def test_option_html_attributes_without_hash - assert_equal({}, option_html_attributes([ 'foo', 'bar' ])) + assert_equal({}, option_html_attributes([ "foo", "bar" ])) end def test_option_html_attributes_with_single_element_hash assert_equal( - {:class => 'fancy'}, - option_html_attributes([ 'foo', 'bar', { :class => 'fancy' } ]) + { class: "fancy" }, + option_html_attributes([ "foo", "bar", { class: "fancy" } ]) ) end def test_option_html_attributes_with_multiple_element_hash assert_equal( - {:class => 'fancy', 'onclick' => "alert('Hello World');"}, - option_html_attributes([ 'foo', 'bar', { :class => 'fancy', 'onclick' => "alert('Hello World');" } ]) + { :class => "fancy", "onclick" => "alert('Hello World');" }, + option_html_attributes([ "foo", "bar", { :class => "fancy", "onclick" => "alert('Hello World');" } ]) ) end def test_option_html_attributes_with_multiple_hashes assert_equal( - {:class => 'fancy', 'onclick' => "alert('Hello World');"}, - option_html_attributes([ 'foo', 'bar', { :class => 'fancy' }, { 'onclick' => "alert('Hello World');" } ]) + { :class => "fancy", "onclick" => "alert('Hello World');" }, + option_html_attributes([ "foo", "bar", { class: "fancy" }, { "onclick" => "alert('Hello World');" } ]) ) end def test_option_html_attributes_with_multiple_hashes_does_not_modify_them - options1 = { class: 'fancy' } + options1 = { class: "fancy" } options2 = { onclick: "alert('Hello World');" } - option_html_attributes([ 'foo', 'bar', options1, options2 ]) + option_html_attributes([ "foo", "bar", options1, options2 ]) - assert_equal({ class: 'fancy' }, options1) + assert_equal({ class: "fancy" }, options1) assert_equal({ onclick: "alert('Hello World');" }, options2) end def test_grouped_collection_select @post = Post.new - @post.origin = 'dk' + @post.origin = "dk" assert_dom_equal( %Q{<select id="post_origin" name="post[origin]"><optgroup label="<Africa>"><option value="<sa>"><South Africa></option>\n<option value="so">Somalia</option></optgroup><optgroup label="Europe"><option value="dk" selected="selected">Denmark</option>\n<option value="ie">Ireland</option></optgroup></select>}, @@ -1348,7 +1410,7 @@ class FormOptionsHelperTest < ActionView::TestCase assert_dom_equal( %Q{<select id="post_origin" name="post[origin]"><optgroup label="<Africa>"><option value="<sa>"><South Africa></option>\n<option value="so">Somalia</option></optgroup><optgroup label="Europe"><option value="dk" selected="selected">Denmark</option>\n<option value="ie">Ireland</option></optgroup></select>}, - grouped_collection_select("post", "origin", dummy_continents, :countries, :continent_name, :country_id, :country_name, :selected => 'dk') + grouped_collection_select("post", "origin", dummy_continents, :countries, :continent_name, :country_id, :country_name, selected: "dk") ) end @@ -1357,13 +1419,13 @@ class FormOptionsHelperTest < ActionView::TestCase assert_dom_equal( %Q{<select id="post_origin" name="post[origin]"><optgroup label="<Africa>"><option value="<sa>"><South Africa></option>\n<option value="so">Somalia</option></optgroup><optgroup label="Europe"><option disabled="disabled" value="dk">Denmark</option>\n<option value="ie">Ireland</option></optgroup></select>}, - grouped_collection_select("post", "origin", dummy_continents, :countries, :continent_name, :country_id, :country_name, :disabled => 'dk') + grouped_collection_select("post", "origin", dummy_continents, :countries, :continent_name, :country_id, :country_name, disabled: "dk") ) end def test_grouped_collection_select_under_fields_for @post = Post.new - @post.origin = 'dk' + @post.origin = "dk" output_buffer = fields_for :post, @post do |f| concat f.grouped_collection_select("origin", dummy_continents, :countries, :continent_name, :country_id, :country_name) @@ -1377,14 +1439,14 @@ class FormOptionsHelperTest < ActionView::TestCase private - def dummy_posts - [ Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"), - Post.new("Babe went home", "Babe", "To a little house", "shh!"), - Post.new("Cabe went home", "Cabe", "To a little house", "shh!") ] - end + def dummy_posts + [ Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"), + Post.new("Babe went home", "Babe", "To a little house", "shh!"), + Post.new("Cabe went home", "Cabe", "To a little house", "shh!") ] + end - def dummy_continents - [ Continent.new("<Africa>", [Country.new("<sa>", "<South Africa>"), Country.new("so", "Somalia")]), - Continent.new("Europe", [Country.new("dk", "Denmark"), Country.new("ie", "Ireland")]) ] - end + def dummy_continents + [ Continent.new("<Africa>", [Country.new("<sa>", "<South Africa>"), Country.new("so", "Somalia")]), + Continent.new("Europe", [Country.new("dk", "Denmark"), Country.new("ie", "Ireland")]) ] + end end diff --git a/actionview/test/template/form_tag_helper_test.rb b/actionview/test/template/form_tag_helper_test.rb index 7b93c8dc29..5e328ebf53 100644 --- a/actionview/test/template/form_tag_helper_test.rb +++ b/actionview/test/template/form_tag_helper_test.rb @@ -1,10 +1,22 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class FormTagHelperTest < ActionView::TestCase include RenderERBUtils tests ActionView::Helpers::FormTagHelper + class WithActiveStorageRoutesControllers < ActionController::Base + test_routes do + post "/rails/active_storage/direct_uploads" => "active_storage/direct_uploads#create", as: :rails_direct_uploads + end + + def url_options + { host: "testtwo.host" } + end + end + def setup super @controller = BasicController.new @@ -14,7 +26,7 @@ class FormTagHelperTest < ActionView::TestCase method = options[:method] enforce_utf8 = options.fetch(:enforce_utf8, true) - ''.tap do |txt| + "".dup.tap do |txt| if enforce_utf8 txt << %{<input name="utf8" type="hidden" value="✓" />} end @@ -30,7 +42,7 @@ class FormTagHelperTest < ActionView::TestCase method = method.to_s == "get" ? "get" : "post" - txt = %{<form accept-charset="UTF-8" action="#{action}"} + txt = %{<form accept-charset="UTF-8" action="#{action}"}.dup txt << %{ enctype="multipart/form-data"} if enctype txt << %{ data-remote="true"} if remote txt << %{ class="#{html_class}"} if html_class @@ -65,20 +77,20 @@ class FormTagHelperTest < ActionView::TestCase end def test_check_box_tag_disabled - actual = check_box_tag "admin","1", false, disabled: true + actual = check_box_tag "admin", "1", false, disabled: true expected = %(<input id="admin" disabled="disabled" name="admin" type="checkbox" value="1" />) assert_dom_equal expected, actual end def test_check_box_tag_default_checked - actual = check_box_tag "admin","1", true + actual = check_box_tag "admin", "1", true expected = %(<input id="admin" checked="checked" name="admin" type="checkbox" value="1" />) assert_dom_equal expected, actual end def test_check_box_tag_id_sanitized label_elem = root_elem(check_box_tag("project[2][admin]")) - assert_match VALID_HTML_ID, label_elem['id'] + assert_match VALID_HTML_ID, label_elem["id"] end def test_form_tag @@ -88,54 +100,54 @@ class FormTagHelperTest < ActionView::TestCase end def test_form_tag_multipart - actual = form_tag({}, { 'multipart' => true }) - expected = whole_form("http://www.example.com", :enctype => true) + actual = form_tag({}, { "multipart" => true }) + expected = whole_form("http://www.example.com", enctype: true) assert_dom_equal expected, actual end def test_form_tag_with_method_patch - actual = form_tag({}, { :method => :patch }) - expected = whole_form("http://www.example.com", :method => :patch) + actual = form_tag({}, { method: :patch }) + expected = whole_form("http://www.example.com", method: :patch) assert_dom_equal expected, actual end def test_form_tag_with_method_put - actual = form_tag({}, { :method => :put }) - expected = whole_form("http://www.example.com", :method => :put) + actual = form_tag({}, { method: :put }) + expected = whole_form("http://www.example.com", method: :put) assert_dom_equal expected, actual end def test_form_tag_with_method_delete - actual = form_tag({}, { :method => :delete }) + actual = form_tag({}, { method: :delete }) - expected = whole_form("http://www.example.com", :method => :delete) + expected = whole_form("http://www.example.com", method: :delete) assert_dom_equal expected, actual end def test_form_tag_with_remote - actual = form_tag({}, :remote => true) + actual = form_tag({}, { remote: true }) - expected = whole_form("http://www.example.com", :remote => true) + expected = whole_form("http://www.example.com", remote: true) assert_dom_equal expected, actual end def test_form_tag_with_remote_false - actual = form_tag({}, :remote => false) + actual = form_tag({}, { remote: false }) expected = whole_form assert_dom_equal expected, actual end def test_form_tag_enforce_utf8_true - actual = form_tag({}, { :enforce_utf8 => true }) - expected = whole_form("http://www.example.com", :enforce_utf8 => true) + actual = form_tag({}, { enforce_utf8: true }) + expected = whole_form("http://www.example.com", enforce_utf8: true) assert_dom_equal expected, actual assert actual.html_safe? end def test_form_tag_enforce_utf8_false - actual = form_tag({}, { :enforce_utf8 => false }) - expected = whole_form("http://www.example.com", :enforce_utf8 => false) + actual = form_tag({}, { enforce_utf8: false }) + expected = whole_form("http://www.example.com", enforce_utf8: false) assert_dom_equal expected, actual assert actual.html_safe? end @@ -150,7 +162,7 @@ class FormTagHelperTest < ActionView::TestCase def test_form_tag_with_block_and_method_in_erb output_buffer = render_erb("<%= form_tag('http://www.example.com', :method => :put) do %>Hello world!<% end %>") - expected = whole_form("http://www.example.com", :method => "put") do + expected = whole_form("http://www.example.com", method: "put") do "Hello world!" end @@ -165,7 +177,7 @@ class FormTagHelperTest < ActionView::TestCase def test_hidden_field_tag_id_sanitized input_elem = root_elem(hidden_field_tag("item[][title]")) - assert_match VALID_HTML_ID, input_elem['id'] + assert_match VALID_HTML_ID, input_elem["id"] end def test_file_field_tag @@ -173,7 +185,34 @@ class FormTagHelperTest < ActionView::TestCase end def test_file_field_tag_with_options - assert_dom_equal "<input name=\"picsplz\" type=\"file\" id=\"picsplz\" class=\"pix\"/>", file_field_tag("picsplz", :class => "pix") + assert_dom_equal "<input name=\"picsplz\" type=\"file\" id=\"picsplz\" class=\"pix\"/>", file_field_tag("picsplz", class: "pix") + end + + def test_file_field_tag_with_direct_upload_when_rails_direct_uploads_url_is_not_defined + assert_dom_equal( + "<input name=\"picsplz\" type=\"file\" id=\"picsplz\" class=\"pix\"/>", + file_field_tag("picsplz", class: "pix", direct_upload: true) + ) + end + + def test_file_field_tag_with_direct_upload_when_rails_direct_uploads_url_is_defined + @controller = WithActiveStorageRoutesControllers.new + + assert_dom_equal( + "<input name=\"picsplz\" type=\"file\" id=\"picsplz\" class=\"pix\" data-direct-upload-url=\"http://testtwo.host/rails/active_storage/direct_uploads\"/>", + file_field_tag("picsplz", class: "pix", direct_upload: true) + ) + end + + def test_file_field_tag_with_direct_upload_dont_mutate_arguments + original_options = { class: "pix", direct_upload: true } + + assert_dom_equal( + "<input name=\"picsplz\" type=\"file\" id=\"picsplz\" class=\"pix\"/>", + file_field_tag("picsplz", original_options) + ) + + assert_equal({ class: "pix", direct_upload: true }, original_options) end def test_password_field_tag @@ -183,7 +222,7 @@ class FormTagHelperTest < ActionView::TestCase end def test_multiple_field_tags_with_same_options - options = {class: 'important'} + options = { class: "important" } assert_dom_equal %(<input name="title" type="file" id="title" class="important"/>), file_field_tag("title", options) assert_dom_equal %(<input type="password" name="title" id="title" value="Hello!" class="important" />), password_field_tag("title", "Hello!", options) assert_dom_equal %(<input type="text" name="title" id="title" value="Hello!" class="important" />), text_field_tag("title", "Hello!", options) @@ -210,7 +249,7 @@ class FormTagHelperTest < ActionView::TestCase expected = %(<input id="person_gender_m" name="person[gender]" type="radio" value="m" />) assert_dom_equal expected, actual - actual = radio_button_tag('ctrlname', 'apache2.2') + actual = radio_button_tag("ctrlname", "apache2.2") expected = %(<input id="ctrlname_apache2.2" name="ctrlname" type="radio" value="apache2.2" />) assert_dom_equal expected, actual end @@ -235,12 +274,12 @@ class FormTagHelperTest < ActionView::TestCase def test_select_tag_id_sanitized input_elem = root_elem(select_tag("project[1]people", "<option>david</option>")) - assert_match VALID_HTML_ID, input_elem['id'] + assert_match VALID_HTML_ID, input_elem["id"] end def test_select_tag_with_include_blank - actual = select_tag "places", raw("<option>Home</option><option>Work</option><option>Pub</option>"), :include_blank => true - expected = %(<select id="places" name="places"><option value=""></option><option>Home</option><option>Work</option><option>Pub</option></select>) + actual = select_tag "places", raw("<option>Home</option><option>Work</option><option>Pub</option>"), include_blank: true + expected = %(<select id="places" name="places"><option value="" label=" "></option><option>Home</option><option>Work</option><option>Pub</option></select>) assert_dom_equal expected, actual end @@ -251,37 +290,37 @@ class FormTagHelperTest < ActionView::TestCase end def test_select_tag_with_include_blank_string - actual = select_tag "places", raw("<option>Home</option><option>Work</option><option>Pub</option>"), include_blank: 'Choose' + actual = select_tag "places", raw("<option>Home</option><option>Work</option><option>Pub</option>"), 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", raw("<option>Home</option><option>Work</option><option>Pub</option>"), :prompt => "string" + actual = select_tag "places", raw("<option>Home</option><option>Work</option><option>Pub</option>"), prompt: "string" expected = %(<select id="places" name="places"><option value="">string</option><option>Home</option><option>Work</option><option>Pub</option></select>) assert_dom_equal expected, actual end def test_select_tag_escapes_prompt - actual = select_tag "places", raw("<option>Home</option><option>Work</option><option>Pub</option>"), :prompt => "<script>alert(1337)</script>" + actual = select_tag "places", raw("<option>Home</option><option>Work</option><option>Pub</option>"), prompt: "<script>alert(1337)</script>" expected = %(<select id="places" name="places"><option value=""><script>alert(1337)</script></option><option>Home</option><option>Work</option><option>Pub</option></select>) assert_dom_equal expected, actual end def test_select_tag_with_prompt_and_include_blank - actual = select_tag "places", raw("<option>Home</option><option>Work</option><option>Pub</option>"), :prompt => "string", :include_blank => true - expected = %(<select name="places" id="places"><option value="">string</option><option value=""></option><option>Home</option><option>Work</option><option>Pub</option></select>) + actual = select_tag "places", raw("<option>Home</option><option>Work</option><option>Pub</option>"), prompt: "string", include_blank: true + expected = %(<select name="places" id="places"><option value="">string</option><option value="" label=" "></option><option>Home</option><option>Work</option><option>Pub</option></select>) assert_dom_equal expected, actual end def test_select_tag_with_nil_option_tags_and_include_blank - actual = select_tag "places", nil, :include_blank => true - expected = %(<select id="places" name="places"><option value=""></option></select>) + actual = select_tag "places", nil, include_blank: true + expected = %(<select id="places" name="places"><option value="" label=" "></option></select>) assert_dom_equal expected, actual end def test_select_tag_with_nil_option_tags_and_prompt - actual = select_tag "places", nil, :prompt => "string" + actual = select_tag "places", nil, prompt: "string" expected = %(<select id="places" name="places"><option value="">string</option></select>) assert_dom_equal expected, actual end @@ -293,36 +332,36 @@ class FormTagHelperTest < ActionView::TestCase end def test_text_area_tag_size_symbol - actual = text_area_tag "body", "hello world", :size => "20x40" + actual = text_area_tag "body", "hello world", size: "20x40" expected = %(<textarea cols="20" id="body" name="body" rows="40">\nhello world</textarea>) assert_dom_equal expected, actual end def test_text_area_tag_should_disregard_size_if_its_given_as_an_integer - actual = text_area_tag "body", "hello world", :size => 20 + actual = text_area_tag "body", "hello world", size: 20 expected = %(<textarea id="body" name="body">\nhello world</textarea>) assert_dom_equal expected, actual end def test_text_area_tag_id_sanitized input_elem = root_elem(text_area_tag("item[][description]")) - assert_match VALID_HTML_ID, input_elem['id'] + assert_match VALID_HTML_ID, input_elem["id"] end def test_text_area_tag_escape_content - actual = text_area_tag "body", "<b>hello world</b>", :size => "20x40" + actual = text_area_tag "body", "<b>hello world</b>", size: "20x40" expected = %(<textarea cols="20" id="body" name="body" rows="40">\n<b>hello world</b></textarea>) assert_dom_equal expected, actual end def test_text_area_tag_unescaped_content - actual = text_area_tag "body", "<b>hello world</b>", :size => "20x40", :escape => false + actual = text_area_tag "body", "<b>hello world</b>", size: "20x40", escape: false expected = %(<textarea cols="20" id="body" name="body" rows="40">\n<b>hello world</b></textarea>) assert_dom_equal expected, actual end def test_text_area_tag_unescaped_nil_content - actual = text_area_tag "body", nil, :escape => false + actual = text_area_tag "body", nil, escape: false expected = %(<textarea id="body" name="body">\n</textarea>) assert_dom_equal expected, actual end @@ -340,11 +379,17 @@ class FormTagHelperTest < ActionView::TestCase end def test_text_field_tag_size_symbol - actual = text_field_tag "title", "Hello!", :size => 75 + actual = text_field_tag "title", "Hello!", size: 75 expected = %(<input id="title" name="title" size="75" type="text" value="Hello!" />) assert_dom_equal expected, actual end + def test_text_field_tag_with_ac_parameters + actual = text_field_tag "title", ActionController::Parameters.new(key: "value") + expected = %(<input id="title" name="title" type="text" value="{"key"=>"value"}" />) + assert_dom_equal expected, actual + end + def test_text_field_tag_size_string actual = text_field_tag "title", "Hello!", "size" => "75" expected = %(<input id="title" name="title" size="75" type="text" value="Hello!" />) @@ -352,7 +397,7 @@ class FormTagHelperTest < ActionView::TestCase end def test_text_field_tag_maxlength_symbol - actual = text_field_tag "title", "Hello!", :maxlength => 75 + actual = text_field_tag "title", "Hello!", maxlength: 75 expected = %(<input id="title" name="title" maxlength="75" type="text" value="Hello!" />) assert_dom_equal expected, actual end @@ -370,20 +415,20 @@ class FormTagHelperTest < ActionView::TestCase end def test_text_field_tag_with_placeholder_option - actual = text_field_tag "title", "Hello!", placeholder: 'Enter search term...' + actual = text_field_tag "title", "Hello!", placeholder: "Enter search term..." expected = %(<input id="title" name="title" placeholder="Enter search term..." type="text" value="Hello!" />) assert_dom_equal expected, actual end def test_text_field_tag_with_multiple_options - actual = text_field_tag "title", "Hello!", :size => 70, :maxlength => 80 + actual = text_field_tag "title", "Hello!", size: 70, maxlength: 80 expected = %(<input id="title" name="title" size="70" maxlength="80" type="text" value="Hello!" />) assert_dom_equal expected, actual end def test_text_field_tag_id_sanitized input_elem = root_elem(text_field_tag("item[][title]")) - assert_match VALID_HTML_ID, input_elem['id'] + assert_match VALID_HTML_ID, input_elem["id"] end def test_label_tag_without_text @@ -412,11 +457,11 @@ class FormTagHelperTest < ActionView::TestCase def test_label_tag_id_sanitized label_elem = root_elem(label_tag("item[title]")) - assert_match VALID_HTML_ID, label_elem['for'] + assert_match VALID_HTML_ID, label_elem["for"] end def test_label_tag_with_block - assert_dom_equal('<label>Blocked</label>', label_tag { "Blocked" }) + assert_dom_equal("<label>Blocked</label>", label_tag { "Blocked" }) end def test_label_tag_with_block_and_argument @@ -425,21 +470,21 @@ class FormTagHelperTest < ActionView::TestCase end def test_label_tag_with_block_and_argument_and_options - output = label_tag("clock", :id => "label_clock") { "Grandfather" } + output = label_tag("clock", id: "label_clock") { "Grandfather" } assert_dom_equal('<label for="clock" id="label_clock">Grandfather</label>', output) end def test_boolean_options - assert_dom_equal %(<input checked="checked" disabled="disabled" id="admin" name="admin" readonly="readonly" type="checkbox" value="1" />), check_box_tag("admin", 1, true, 'disabled' => true, :readonly => "yes") - assert_dom_equal %(<input checked="checked" id="admin" name="admin" type="checkbox" value="1" />), check_box_tag("admin", 1, true, :disabled => false, :readonly => nil) - assert_dom_equal %(<input type="checkbox" />), tag(:input, :type => "checkbox", :checked => false) - assert_dom_equal %(<select id="people" multiple="multiple" name="people[]"><option>david</option></select>), select_tag("people", raw("<option>david</option>"), :multiple => true) - assert_dom_equal %(<select id="people_" multiple="multiple" name="people[]"><option>david</option></select>), select_tag("people[]", raw("<option>david</option>"), :multiple => true) - assert_dom_equal %(<select id="people" name="people"><option>david</option></select>), select_tag("people", raw("<option>david</option>"), :multiple => nil) + assert_dom_equal %(<input checked="checked" disabled="disabled" id="admin" name="admin" readonly="readonly" type="checkbox" value="1" />), check_box_tag("admin", 1, true, "disabled" => true, :readonly => "yes") + assert_dom_equal %(<input checked="checked" id="admin" name="admin" type="checkbox" value="1" />), check_box_tag("admin", 1, true, disabled: false, readonly: nil) + assert_dom_equal %(<input type="checkbox" />), tag(:input, type: "checkbox", checked: false) + assert_dom_equal %(<select id="people" multiple="multiple" name="people[]"><option>david</option></select>), select_tag("people", raw("<option>david</option>"), multiple: true) + assert_dom_equal %(<select id="people_" multiple="multiple" name="people[]"><option>david</option></select>), select_tag("people[]", raw("<option>david</option>"), multiple: true) + assert_dom_equal %(<select id="people" name="people"><option>david</option></select>), select_tag("people", raw("<option>david</option>"), multiple: nil) end def test_stringify_symbol_keys - actual = text_field_tag "title", "Hello!", :id => "admin" + actual = text_field_tag "title", "Hello!", id: "admin" expected = %(<input id="admin" name="title" type="text" value="Hello!" />) assert_dom_equal expected, actual end @@ -447,7 +492,7 @@ class FormTagHelperTest < ActionView::TestCase def test_submit_tag assert_dom_equal( %(<input name='commit' data-disable-with="Saving..." onclick="alert('hello!')" type="submit" value="Save" />), - submit_tag("Save", :onclick => "alert('hello!')", :data => { :disable_with => "Saving..." }) + submit_tag("Save", onclick: "alert('hello!')", data: { disable_with: "Saving..." }) ) end @@ -471,42 +516,49 @@ class FormTagHelperTest < ActionView::TestCase def test_submit_tag_having_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?" }) + submit_tag("Save", "data-disable-with" => "Processing...", "data-confirm" => "Are you sure?") ) end def test_submit_tag_having_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?" }) + submit_tag("Save", "data-disable-with" => false, "data-confirm" => "Are you sure?") ) end def test_submit_tag_having_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 } }) + 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" />), - submit_tag("Save", :data => { :disable_with => "Saving..." }) + submit_tag("Save", data: { disable_with: "Saving..." }) ) end def test_submit_tag_with_confirmation assert_dom_equal( %(<input name='commit' type='submit' value='Save' data-confirm="Are you sure?" data-disable-with="Save" />), - submit_tag("Save", :data => { :confirm => "Are you sure?" }) + submit_tag("Save", data: { confirm: "Are you sure?" }) ) end def test_submit_tag_doesnt_have_data_disable_with_twice assert_equal( %(<input type="submit" name="commit" value="Save" data-confirm="Are you sure?" data-disable-with="Processing..." />), - submit_tag("Save", { "data-disable-with" => "Processing...", "data-confirm" => "Are you sure?" }) + submit_tag("Save", "data-disable-with" => "Processing...", "data-confirm" => "Are you sure?") + ) + end + + def test_submit_tag_doesnt_have_data_disable_with_twice_with_hash + assert_equal( + %(<input type="submit" name="commit" value="Save" data-disable-with="Processing..." />), + submit_tag("Save", data: { disable_with: "Processing..." }) ) end @@ -517,7 +569,6 @@ class FormTagHelperTest < ActionView::TestCase ) end - def test_button_tag assert_dom_equal( %(<button name="button" type="submit">Button</button>), @@ -528,56 +579,56 @@ class FormTagHelperTest < ActionView::TestCase def test_button_tag_with_submit_type assert_dom_equal( %(<button name="button" type="submit">Save</button>), - button_tag("Save", :type => "submit") + button_tag("Save", type: "submit") ) end def test_button_tag_with_button_type assert_dom_equal( %(<button name="button" type="button">Button</button>), - button_tag("Button", :type => "button") + button_tag("Button", type: "button") ) end def test_button_tag_with_reset_type assert_dom_equal( %(<button name="button" type="reset">Reset</button>), - button_tag("Reset", :type => "reset") + button_tag("Reset", type: "reset") ) end def test_button_tag_with_disabled_option assert_dom_equal( %(<button name="button" type="reset" disabled="disabled">Reset</button>), - button_tag("Reset", :type => "reset", :disabled => true) + button_tag("Reset", type: "reset", disabled: true) ) end def test_button_tag_escape_content assert_dom_equal( %(<button name="button" type="reset" disabled="disabled"><b>Reset</b></button>), - button_tag("<b>Reset</b>", :type => "reset", :disabled => true) + button_tag("<b>Reset</b>", type: "reset", disabled: true) ) end def test_button_tag_with_block - assert_dom_equal('<button name="button" type="submit">Content</button>', button_tag { 'Content' }) + assert_dom_equal('<button name="button" type="submit">Content</button>', button_tag { "Content" }) end def test_button_tag_with_block_and_options - output = button_tag(:name => 'temptation', :type => 'button') { content_tag(:strong, 'Do not press me') } + output = button_tag(name: "temptation", type: "button") { content_tag(:strong, "Do not press me") } assert_dom_equal('<button name="temptation" type="button"><strong>Do not press me</strong></button>', output) end def test_button_tag_defaults_with_block_and_options - output = button_tag(:name => 'temptation', :value => 'within') { content_tag(:strong, 'Do not press me') } + output = button_tag(name: "temptation", value: "within") { content_tag(:strong, "Do not press me") } assert_dom_equal('<button name="temptation" value="within" type="submit" ><strong>Do not press me</strong></button>', output) end def test_button_tag_with_confirmation assert_dom_equal( %(<button name="button" type="submit" data-confirm="Are you sure?">Save</button>), - button_tag("Save", :type => "submit", :data => { :confirm => "Are you sure?" }) + button_tag("Save", type: "submit", data: { confirm: "Are you sure?" }) ) end @@ -590,8 +641,8 @@ class FormTagHelperTest < ActionView::TestCase def test_image_submit_tag_with_confirmation assert_dom_equal( - %(<input alt="Save" type="image" src="/images/save.gif" data-confirm="Are you sure?" />), - image_submit_tag("save.gif", :data => { :confirm => "Are you sure?" }) + %(<input type="image" src="/images/save.gif" data-confirm="Are you sure?" />), + image_submit_tag("save.gif", data: { confirm: "Are you sure?" }) ) end @@ -621,10 +672,8 @@ class FormTagHelperTest < ActionView::TestCase end def test_datetime_field_tag - expected = %{<input id="appointment" name="appointment" type="datetime" />} - assert_deprecated do - assert_dom_equal(expected, datetime_field_tag("appointment")) - end + expected = %{<input id="appointment" name="appointment" type="datetime-local" />} + assert_dom_equal(expected, datetime_field_tag("appointment")) end def test_datetime_local_field_tag @@ -654,12 +703,12 @@ class FormTagHelperTest < ActionView::TestCase def test_number_field_tag expected = %{<input name="quantity" max="9" id="quantity" type="number" min="1" />} - assert_dom_equal(expected, number_field_tag("quantity", nil, :in => 1...10)) + assert_dom_equal(expected, number_field_tag("quantity", nil, in: 1...10)) end def test_range_input_tag expected = %{<input name="volume" step="0.1" max="11" id="volume" type="range" min="0" />} - assert_dom_equal(expected, range_field_tag("volume", nil, :in => 0..11, :step => 0.1)) + assert_dom_equal(expected, range_field_tag("volume", nil, in: 0..11, step: 0.1)) end def test_field_set_tag_in_erb @@ -695,33 +744,33 @@ class FormTagHelperTest < ActionView::TestCase end def test_text_area_tag_options_symbolize_keys_side_effects - options = { :option => "random_option" } + options = { option: "random_option" } text_area_tag "body", "hello world", options - assert_equal options, { :option => "random_option" } + assert_equal({ option: "random_option" }, options) end def test_submit_tag_options_symbolize_keys_side_effects - options = { :option => "random_option" } + options = { option: "random_option" } submit_tag "submit value", options - assert_equal options, { :option => "random_option" } + assert_equal({ option: "random_option" }, options) end def test_button_tag_options_symbolize_keys_side_effects - options = { :option => "random_option" } + options = { option: "random_option" } button_tag "button value", options - assert_equal options, { :option => "random_option" } + assert_equal({ option: "random_option" }, options) end def test_image_submit_tag_options_symbolize_keys_side_effects - options = { :option => "random_option" } + options = { option: "random_option" } image_submit_tag "submit source", options - assert_equal options, { :option => "random_option" } + assert_equal({ option: "random_option" }, options) end def test_image_label_tag_options_symbolize_keys_side_effects - options = { :option => "random_option" } + options = { option: "random_option" } label_tag "submit source", "title", options - assert_equal options, { :option => "random_option" } + assert_equal({ option: "random_option" }, options) end def protect_against_forgery? @@ -730,7 +779,7 @@ class FormTagHelperTest < ActionView::TestCase private - def root_elem(rendered_content) - Nokogiri::HTML::DocumentFragment.parse(rendered_content).children.first # extract from nodeset - end + def root_elem(rendered_content) + Nokogiri::HTML::DocumentFragment.parse(rendered_content).children.first # extract from nodeset + end end diff --git a/actionview/test/template/html_test.rb b/actionview/test/template/html_test.rb index 549c12c88c..5cdff74d60 100644 --- a/actionview/test/template/html_test.rb +++ b/actionview/test/template/html_test.rb @@ -1,17 +1,19 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class HTMLTest < ActiveSupport::TestCase - test 'formats returns symbol for recognized MIME type' do - assert_equal [:html], ActionView::Template::HTML.new('', :html).formats + test "formats returns symbol for recognized MIME type" do + assert_equal [:html], ActionView::Template::HTML.new("", :html).formats end - test 'formats returns string for recognized MIME type when MIME does not have symbol' do + test "formats returns string for recognized MIME type when MIME does not have symbol" do foo = Mime::Type.lookup("foo") assert_nil foo.to_sym - assert_equal ['foo'], ActionView::Template::HTML.new('', foo).formats + assert_equal ["foo"], ActionView::Template::HTML.new("", foo).formats end - test 'formats returns string for unknown MIME type' do - assert_equal ['foo'], ActionView::Template::HTML.new('', 'foo').formats + test "formats returns string for unknown MIME type" do + assert_equal ["foo"], ActionView::Template::HTML.new("", "foo").formats end end diff --git a/actionview/test/template/javascript_helper_test.rb b/actionview/test/template/javascript_helper_test.rb index 9f1535ef53..a72bc6c2fe 100644 --- a/actionview/test/template/javascript_helper_test.rb +++ b/actionview/test/template/javascript_helper_test.rb @@ -1,14 +1,20 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class JavaScriptHelperTest < ActionView::TestCase tests ActionView::Helpers::JavaScriptHelper attr_accessor :output_buffer + attr_reader :request setup do @old_escape_html_entities_in_json = ActiveSupport.escape_html_entities_in_json - ActiveSupport.escape_html_entities_in_json = true + ActiveSupport.escape_html_entities_in_json = true @template = self + @request = Class.new do + def send_early_hints(links) end + end.new end def teardown @@ -16,12 +22,12 @@ class JavaScriptHelperTest < ActionView::TestCase end def test_escape_javascript - assert_equal '', escape_javascript(nil) + assert_equal "", escape_javascript(nil) assert_equal %(This \\"thing\\" is really\\n netos\\'), escape_javascript(%(This "thing" is really\n netos')) - assert_equal %(backslash\\\\test), escape_javascript( %(backslash\\test) ) + assert_equal %(backslash\\\\test), escape_javascript(%(backslash\\test)) assert_equal %(dont <\\/close> tags), escape_javascript(%(dont </close> tags)) - assert_equal %(unicode 
 newline), escape_javascript(%(unicode \342\200\250 newline).force_encoding(Encoding::UTF_8).encode!) - assert_equal %(unicode 
 newline), escape_javascript(%(unicode \342\200\251 newline).force_encoding(Encoding::UTF_8).encode!) + assert_equal %(unicode 
 newline), escape_javascript(%(unicode \342\200\250 newline).dup.force_encoding(Encoding::UTF_8).encode!) + assert_equal %(unicode 
 newline), escape_javascript(%(unicode \342\200\251 newline).dup.force_encoding(Encoding::UTF_8).encode!) assert_equal %(dont <\\/close> tags), j(%(dont </close> tags)) end @@ -36,24 +42,24 @@ class JavaScriptHelperTest < ActionView::TestCase end def test_javascript_tag - self.output_buffer = 'foo' + self.output_buffer = "foo" assert_dom_equal "<script>\n//<![CDATA[\nalert('hello')\n//]]>\n</script>", javascript_tag("alert('hello')") - assert_equal 'foo', output_buffer, 'javascript_tag without a block should not concat to output_buffer' + assert_equal "foo", output_buffer, "javascript_tag without a block should not concat to output_buffer" end # Setting the :extname option will control what extension (if any) is appended to the url for assets def test_javascript_include_tag - assert_dom_equal "<script src='/foo.js'></script>", javascript_include_tag('/foo') - assert_dom_equal "<script src='/foo'></script>", javascript_include_tag('/foo', extname: false ) - assert_dom_equal "<script src='/foo.bar'></script>", javascript_include_tag('/foo', extname: '.bar' ) + assert_dom_equal "<script src='/foo.js'></script>", javascript_include_tag("/foo") + assert_dom_equal "<script src='/foo'></script>", javascript_include_tag("/foo", extname: false) + assert_dom_equal "<script src='/foo.bar'></script>", javascript_include_tag("/foo", extname: ".bar") end def test_javascript_tag_with_options assert_dom_equal "<script id=\"the_js_tag\">\n//<![CDATA[\nalert('hello')\n//]]>\n</script>", - javascript_tag("alert('hello')", :id => "the_js_tag") + javascript_tag("alert('hello')", id: "the_js_tag") end def test_javascript_cdata_section diff --git a/actionview/test/template/log_subscriber_test.rb b/actionview/test/template/log_subscriber_test.rb index 7683444bf0..7f4fd25573 100644 --- a/actionview/test/template/log_subscriber_test.rb +++ b/actionview/test/template/log_subscriber_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "abstract_unit" require "active_support/log_subscriber/test_helper" require "action_view/log_subscriber" @@ -8,11 +10,14 @@ class AVLogSubscriberTest < ActiveSupport::TestCase def setup super - view_paths = ActionController::Base.view_paths + + view_paths = ActionController::Base.view_paths lookup_context = ActionView::LookupContext.new(view_paths, {}, ["test"]) - renderer = ActionView::Renderer.new(lookup_context) - @view = ActionView::Base.new(renderer, {}) + renderer = ActionView::Renderer.new(lookup_context) + @view = ActionView::Base.new(renderer, {}) + ActionView::LogSubscriber.attach_to :action_view + unless Rails.respond_to?(:root) @defined_root = true def Rails.root; :defined_root; end # Minitest `stub` expects the method to be defined. @@ -21,18 +26,32 @@ class AVLogSubscriberTest < ActiveSupport::TestCase def teardown super + ActiveSupport::LogSubscriber.log_subscribers.clear + # We need to undef `root`, RenderTestCases don't want this to be defined - Rails.instance_eval { undef :root } if @defined_root + Rails.instance_eval { undef :root } if defined?(@defined_root) end def set_logger(logger) ActionView::Base.logger = logger end + def set_cache_controller + controller = ActionController::Base.new + controller.perform_caching = true + controller.cache_store = ActiveSupport::Cache::MemoryStore.new + @view.controller = controller + end + + def set_view_cache_dependencies + def @view.view_cache_dependencies; []; end + def @view.combined_fragment_cache_key(*); "ahoy `controller` dependency"; end + end + def test_render_file_template Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do - @view.render(:file => "test/hello_world") + @view.render(file: "test/hello_world") wait assert_equal 2, @logger.logged(:info).size @@ -43,7 +62,7 @@ class AVLogSubscriberTest < ActiveSupport::TestCase def test_render_text_template Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do - @view.render(:text => "TEXT") + @view.render(plain: "TEXT") wait assert_equal 2, @logger.logged(:info).size @@ -54,7 +73,7 @@ class AVLogSubscriberTest < ActiveSupport::TestCase def test_render_inline_template Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do - @view.render(:inline => "<%= 'TEXT' %>") + @view.render(inline: "<%= 'TEXT' %>") wait assert_equal 2, @logger.logged(:info).size @@ -63,29 +82,106 @@ class AVLogSubscriberTest < ActiveSupport::TestCase end end - def test_render_partial_template + def test_render_partial_with_implicit_path Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do - @view.render(:partial => "test/customer") + @view.render(Customer.new("david"), greeting: "hi") wait assert_equal 1, @logger.logged(:info).size - assert_match(/Rendered test\/_customer.erb/, @logger.logged(:info).last) + assert_match(/Rendered customers\/_customer\.html\.erb/, @logger.logged(:info).last) end end - def test_render_partial_with_implicit_path + def test_render_partial_with_cache_missed Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do - @view.render(Customer.new("david"), :greeting => "hi") + set_view_cache_dependencies + set_cache_controller + + @view.render(partial: "test/cached_customer", locals: { cached_customer: Customer.new("david") }) wait assert_equal 1, @logger.logged(:info).size - assert_match(/Rendered customers\/_customer\.html\.erb/, @logger.logged(:info).last) + assert_match(/Rendered test\/_cached_customer\.erb (.*) \[cache miss\]/, @logger.logged(:info).last) + end + end + + def test_render_partial_with_cache_hitted + Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do + set_view_cache_dependencies + set_cache_controller + + # Second render should hit cache. + @view.render(partial: "test/cached_customer", locals: { cached_customer: Customer.new("david") }) + @view.render(partial: "test/cached_customer", locals: { cached_customer: Customer.new("david") }) + wait + + assert_equal 2, @logger.logged(:info).size + assert_match(/Rendered test\/_cached_customer\.erb (.*) \[cache hit\]/, @logger.logged(:info).last) + end + end + + def test_render_uncached_outer_partial_with_inner_cached_partial_wont_mix_cache_hits_or_misses + Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do + set_view_cache_dependencies + set_cache_controller + + @view.render(partial: "test/nested_cached_customer", locals: { cached_customer: Customer.new("Stan") }) + wait + *, cached_inner, uncached_outer = @logger.logged(:info) + assert_match(/Rendered test\/_cached_customer\.erb (.*) \[cache miss\]/, cached_inner) + assert_match(/Rendered test\/_nested_cached_customer\.erb \(.*?ms\)$/, uncached_outer) + + # Second render hits the cache for the _cached_customer partial. Outer template's log shouldn't be affected. + @view.render(partial: "test/nested_cached_customer", locals: { cached_customer: Customer.new("Stan") }) + wait + *, cached_inner, uncached_outer = @logger.logged(:info) + assert_match(/Rendered test\/_cached_customer\.erb (.*) \[cache hit\]/, cached_inner) + assert_match(/Rendered test\/_nested_cached_customer\.erb \(.*?ms\)$/, uncached_outer) + end + end + + def test_render_cached_outer_partial_with_cached_inner_partial + Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do + set_view_cache_dependencies + set_cache_controller + + @view.render(partial: "test/cached_nested_cached_customer", locals: { cached_customer: Customer.new("Stan") }) + wait + *, cached_inner, cached_outer = @logger.logged(:info) + assert_match(/Rendered test\/_cached_customer\.erb (.*) \[cache miss\]/, cached_inner) + assert_match(/Rendered test\/_cached_nested_cached_customer\.erb (.*) \[cache miss\]/, cached_outer) + + # One render: inner partial skipped, because the outer has been cached. + assert_difference -> { @logger.logged(:info).size }, +1 do + @view.render(partial: "test/cached_nested_cached_customer", locals: { cached_customer: Customer.new("Stan") }) + wait + end + assert_match(/Rendered test\/_cached_nested_cached_customer\.erb (.*) \[cache hit\]/, @logger.logged(:info).last) + end + end + + def test_render_partial_with_cache_hitted_and_missed + Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do + set_view_cache_dependencies + set_cache_controller + + @view.render(partial: "test/cached_customer", locals: { cached_customer: Customer.new("david") }) + wait + assert_match(/Rendered test\/_cached_customer\.erb (.*) \[cache miss\]/, @logger.logged(:info).last) + + @view.render(partial: "test/cached_customer", locals: { cached_customer: Customer.new("david") }) + wait + assert_match(/Rendered test\/_cached_customer\.erb (.*) \[cache hit\]/, @logger.logged(:info).last) + + @view.render(partial: "test/cached_customer", locals: { cached_customer: Customer.new("Stan") }) + wait + assert_match(/Rendered test\/_cached_customer\.erb (.*) \[cache miss\]/, @logger.logged(:info).last) end end def test_render_collection_template Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do - @view.render(:partial => "test/customer", :collection => [ Customer.new("david"), Customer.new("mary") ]) + @view.render(partial: "test/customer", collection: [ Customer.new("david"), Customer.new("mary") ]) wait assert_equal 1, @logger.logged(:info).size @@ -95,7 +191,7 @@ class AVLogSubscriberTest < ActiveSupport::TestCase def test_render_collection_with_implicit_path Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do - @view.render([ Customer.new("david"), Customer.new("mary") ], :greeting => "hi") + @view.render([ Customer.new("david"), Customer.new("mary") ], greeting: "hi") wait assert_equal 1, @logger.logged(:info).size @@ -105,7 +201,7 @@ class AVLogSubscriberTest < ActiveSupport::TestCase def test_render_collection_template_without_path Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do - @view.render([ GoodCustomer.new("david"), Customer.new("mary") ], :greeting => "hi") + @view.render([ GoodCustomer.new("david"), Customer.new("mary") ], greeting: "hi") wait assert_equal 1, @logger.logged(:info).size @@ -115,11 +211,10 @@ class AVLogSubscriberTest < ActiveSupport::TestCase def test_render_collection_with_cached_set Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do - def @view.view_cache_dependencies; []; end - def @view.fragment_cache_key(*); 'ahoy `controller` dependency'; end + set_view_cache_dependencies - @view.render(partial: 'customers/customer', collection: [ Customer.new('david'), Customer.new('mary') ], cached: true, - locals: { greeting: 'hi' }) + @view.render(partial: "customers/customer", collection: [ Customer.new("david"), Customer.new("mary") ], cached: true, + locals: { greeting: "hi" }) wait assert_equal 1, @logger.logged(:info).size diff --git a/actionview/test/template/lookup_context_test.rb b/actionview/test/template/lookup_context_test.rb index 2e3a3f9bae..402ee9b6ae 100644 --- a/actionview/test/template/lookup_context_test.rb +++ b/actionview/test/template/lookup_context_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "abstract_unit" require "abstract_controller/rendering" @@ -120,8 +122,8 @@ class LookupContextTest < ActiveSupport::TestCase @lookup_context.with_fallbacks do assert_equal 3, @lookup_context.view_paths.size - assert @lookup_context.view_paths.include?(ActionView::FallbackFileSystemResolver.new("")) - assert @lookup_context.view_paths.include?(ActionView::FallbackFileSystemResolver.new("/")) + assert_includes @lookup_context.view_paths, ActionView::FallbackFileSystemResolver.new("") + assert_includes @lookup_context.view_paths, ActionView::FallbackFileSystemResolver.new("/") end end @@ -279,10 +281,9 @@ class TestMissingTemplate < ActiveSupport::TestCase test "if a single prefix is passed as a string and the lookup fails, MissingTemplate accepts it" do e = assert_raise ActionView::MissingTemplate do - details = {:handlers=>[], :formats=>[], :variants=>[], :locale=>[]} + details = { handlers: [], formats: [], variants: [], locale: [] } @lookup_context.view_paths.find("foo", "parent", true, details) end assert_match %r{Missing partial parent/_foo with .* Searched in:\n \* "/Path/to/views"\n}, e.message end - end diff --git a/actionview/test/template/number_helper_test.rb b/actionview/test/template/number_helper_test.rb index ace3e950b8..e92bf66203 100644 --- a/actionview/test/template/number_helper_test.rb +++ b/actionview/test/template/number_helper_test.rb @@ -1,10 +1,12 @@ +# frozen_string_literal: true + require "abstract_unit" class NumberHelperTest < ActionView::TestCase tests ActionView::Helpers::NumberHelper def test_number_to_phone - assert_equal nil, number_to_phone(nil) + assert_nil number_to_phone(nil) assert_equal "555-1234", number_to_phone(5551234) assert_equal "(800) 555-1212 x 123", number_to_phone(8005551212, area_code: true, extension: 123) assert_equal "+18005551212", number_to_phone(8005551212, country_code: 1, delimiter: "") @@ -13,23 +15,23 @@ class NumberHelperTest < ActionView::TestCase end def test_number_to_currency - assert_equal nil, number_to_currency(nil) + assert_nil number_to_currency(nil) assert_equal "$1,234,567,890.50", number_to_currency(1234567890.50) assert_equal "$1,234,567,892", number_to_currency(1234567891.50, precision: 0) assert_equal "1,234,567,890.50 - Kč", number_to_currency("-1234567890.50", unit: raw("Kč"), format: "%n %u", negative_format: "%n - %u") assert_equal "&pound;1,234,567,890.50", number_to_currency("1234567890.50", unit: "£") 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") + 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 - assert_equal nil, number_to_percentage(nil) + assert_nil number_to_percentage(nil) assert_equal "100.000%", number_to_percentage(100) - assert_equal "100.000 %", number_to_percentage(100, format: '%n %') - assert_equal "<b>100.000</b> %", number_to_percentage(100, format: '<b>%n</b> %') - assert_equal "<b>100.000</b> %", number_to_percentage(100, format: raw('<b>%n</b> %')) + assert_equal "100.000 %", number_to_percentage(100, format: "%n %") + assert_equal "<b>100.000</b> %", number_to_percentage(100, format: "<b>%n</b> %") + assert_equal "<b>100.000</b> %", number_to_percentage(100, format: raw("<b>%n</b> %")) assert_equal "100%", number_to_percentage(100, precision: 0) assert_equal "123.4%", number_to_percentage(123.400, precision: 3, strip_insignificant_zeros: true) assert_equal "1.000,000%", number_to_percentage(1000, delimiter: ".", separator: ",") @@ -43,13 +45,13 @@ class NumberHelperTest < ActionView::TestCase end def test_number_with_delimiter - assert_equal nil, number_with_delimiter(nil) + assert_nil number_with_delimiter(nil) assert_equal "12,345,678", number_with_delimiter(12345678) assert_equal "0", number_with_delimiter(0) end def test_number_with_precision - assert_equal nil, number_with_precision(nil) + assert_nil number_with_precision(nil) assert_equal "-111.235", number_with_precision(-111.2346) assert_equal "111.00", number_with_precision(111, precision: 2) assert_equal "0.00100", number_with_precision(0.001, precision: 5) @@ -57,13 +59,13 @@ class NumberHelperTest < ActionView::TestCase end def test_number_to_human_size - assert_equal nil, number_to_human_size(nil) + assert_nil number_to_human_size(nil) assert_equal "3 Bytes", number_to_human_size(3.14159265) assert_equal "1.2 MB", number_to_human_size(1234567, precision: 2) end def test_number_to_human - assert_equal nil, number_to_human(nil) + assert_nil number_to_human(nil) assert_equal "0", number_to_human(0) assert_equal "1.23 Thousand", number_to_human(1234) assert_equal "489.0 Thousand", number_to_human(489000, precision: 4, strip_insignificant_zeros: false) @@ -71,27 +73,27 @@ class NumberHelperTest < ActionView::TestCase def test_number_to_human_escape_units volume = { unit: "<b>ml</b>", thousand: "<b>lt</b>", million: "<b>m3</b>", trillion: "<b>km3</b>", quadrillion: "<b>Pl</b>" } - assert_equal '123 <b>lt</b>', number_to_human(123456, :units => volume) - assert_equal '12 <b>ml</b>', number_to_human(12, :units => volume) - assert_equal '1.23 <b>m3</b>', number_to_human(1234567, :units => volume) - assert_equal '1.23 <b>km3</b>', number_to_human(1_234_567_000_000, :units => volume) - assert_equal '1.23 <b>Pl</b>', number_to_human(1_234_567_000_000_000, :units => volume) + assert_equal "123 <b>lt</b>", number_to_human(123456, units: volume) + assert_equal "12 <b>ml</b>", number_to_human(12, units: volume) + assert_equal "1.23 <b>m3</b>", number_to_human(1234567, units: volume) + assert_equal "1.23 <b>km3</b>", number_to_human(1_234_567_000_000, units: volume) + assert_equal "1.23 <b>Pl</b>", number_to_human(1_234_567_000_000_000, units: volume) - #Including fractionals + # Including fractionals distance = { mili: "<b>mm</b>", centi: "<b>cm</b>", deci: "<b>dm</b>", unit: "<b>m</b>", ten: "<b>dam</b>", hundred: "<b>hm</b>", thousand: "<b>km</b>", - micro: "<b>um</b>", nano: "<b>nm</b>", pico: "<b>pm</b>", femto: "<b>fm</b>"} - assert_equal '1.23 <b>mm</b>', number_to_human(0.00123, :units => distance) - assert_equal '1.23 <b>cm</b>', number_to_human(0.0123, :units => distance) - assert_equal '1.23 <b>dm</b>', number_to_human(0.123, :units => distance) - assert_equal '1.23 <b>m</b>', number_to_human(1.23, :units => distance) - assert_equal '1.23 <b>dam</b>', number_to_human(12.3, :units => distance) - assert_equal '1.23 <b>hm</b>', number_to_human(123, :units => distance) - assert_equal '1.23 <b>km</b>', number_to_human(1230, :units => distance) - assert_equal '1.23 <b>um</b>', number_to_human(0.00000123, :units => distance) - assert_equal '1.23 <b>nm</b>', number_to_human(0.00000000123, :units => distance) - assert_equal '1.23 <b>pm</b>', number_to_human(0.00000000000123, :units => distance) - assert_equal '1.23 <b>fm</b>', number_to_human(0.00000000000000123, :units => distance) + micro: "<b>um</b>", nano: "<b>nm</b>", pico: "<b>pm</b>", femto: "<b>fm</b>" } + assert_equal "1.23 <b>mm</b>", number_to_human(0.00123, units: distance) + assert_equal "1.23 <b>cm</b>", number_to_human(0.0123, units: distance) + assert_equal "1.23 <b>dm</b>", number_to_human(0.123, units: distance) + assert_equal "1.23 <b>m</b>", number_to_human(1.23, units: distance) + assert_equal "1.23 <b>dam</b>", number_to_human(12.3, units: distance) + assert_equal "1.23 <b>hm</b>", number_to_human(123, units: distance) + assert_equal "1.23 <b>km</b>", number_to_human(1230, units: distance) + assert_equal "1.23 <b>um</b>", number_to_human(0.00000123, units: distance) + assert_equal "1.23 <b>nm</b>", number_to_human(0.00000000123, units: distance) + assert_equal "1.23 <b>pm</b>", number_to_human(0.00000000000123, units: distance) + assert_equal "1.23 <b>fm</b>", number_to_human(0.00000000000000123, units: distance) end def test_number_helpers_escape_delimiter_and_separator @@ -116,9 +118,9 @@ class NumberHelperTest < ActionView::TestCase end def test_number_to_human_with_custom_translation_scope - I18n.backend.store_translations 'ts', - :custom_units_for_number_to_human => {:mili => "mm", :centi => "cm", :deci => "dm", :unit => "m", :ten => "dam", :hundred => "hm", :thousand => "km"} - assert_equal "1.01 cm", number_to_human(0.0101, :locale => 'ts', :units => :custom_units_for_number_to_human) + I18n.backend.store_translations "ts", + custom_units_for_number_to_human: { mili: "mm", centi: "cm", deci: "dm", unit: "m", ten: "dam", hundred: "hm", thousand: "km" } + assert_equal "1.01 cm", number_to_human(0.0101, locale: "ts", units: :custom_units_for_number_to_human) ensure I18n.reload! end diff --git a/actionview/test/template/output_safety_helper_test.rb b/actionview/test/template/output_safety_helper_test.rb index b940c9dd36..b5e9a77105 100644 --- a/actionview/test/template/output_safety_helper_test.rb +++ b/actionview/test/template/output_safety_helper_test.rb @@ -1,4 +1,6 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class OutputSafetyHelperTest < ActionView::TestCase tests ActionView::Helpers::OutputSafetyHelper @@ -26,11 +28,27 @@ class OutputSafetyHelperTest < ActionView::TestCase end test "safe_join should work recursively similarly to Array.join" do - joined = safe_join(['a',['b','c']], ':') - assert_equal 'a:b:c', joined + joined = safe_join(["a", ["b", "c"]], ":") + assert_equal "a:b:c", joined - joined = safe_join(['"a"',['<b>','<c>']], ' <br/> ') - assert_equal '"a" <br/> <b> <br/> <c>', joined + joined = safe_join(['"a"', ["<b>", "<c>"]], " <br/> ") + assert_equal ""a" <br/> <b> <br/> <c>", joined + end + + test "safe_join should return the safe string separated by $, when second argument is not passed" do + default_delimeter = $, + + begin + $, = nil + joined = safe_join(["a", "b"]) + assert_equal "ab", joined + + $, = "|" + joined = safe_join(["a", "b"]) + assert_equal "a|b", joined + ensure + $, = default_delimeter + end end test "to_sentence should escape non-html_safe values" do @@ -50,9 +68,9 @@ class OutputSafetyHelperTest < ActionView::TestCase end test "to_sentence connector words are checked for html safety" do - assert_equal "one & two, and three", to_sentence(['one', 'two', 'three'], words_connector: ' & '.html_safe) - assert_equal "one & two", to_sentence(['one', 'two'], two_words_connector: ' & '.html_safe) - assert_equal "one, two <script>alert(1)</script> three", to_sentence(['one', 'two', 'three'], last_word_connector: ' <script>alert(1)</script> ') + assert_equal "one & two, and three", to_sentence(["one", "two", "three"], words_connector: " & ".html_safe) + assert_equal "one & two", to_sentence(["one", "two"], two_words_connector: " & ".html_safe) + assert_equal "one, two <script>alert(1)</script> three", to_sentence(["one", "two", "three"], last_word_connector: " <script>alert(1)</script> ") end test "to_sentence should not escape html_safe values" do @@ -67,24 +85,35 @@ class OutputSafetyHelperTest < ActionView::TestCase end test "to_sentence handles blank strings" do - actual = to_sentence(['', 'two', 'three']) + actual = to_sentence(["", "two", "three"]) assert actual.html_safe? assert_equal ", two, and three", actual end test "to_sentence handles nil values" do - actual = to_sentence([nil, 'two', 'three']) + actual = to_sentence([nil, "two", "three"]) assert actual.html_safe? assert_equal ", two, and three", actual end test "to_sentence still supports ActiveSupports Array#to_sentence arguments" do - assert_equal "one two, and three", to_sentence(['one', 'two', 'three'], words_connector: ' ') - assert_equal "one & two, and three", to_sentence(['one', 'two', 'three'], words_connector: ' & '.html_safe) - assert_equal "onetwo, and three", to_sentence(['one', 'two', 'three'], words_connector: nil) - assert_equal "one, two, and also three", to_sentence(['one', 'two', 'three'], last_word_connector: ', and also ') - assert_equal "one, twothree", to_sentence(['one', 'two', 'three'], last_word_connector: nil) - assert_equal "one, two three", to_sentence(['one', 'two', 'three'], last_word_connector: ' ') - assert_equal "one, two and three", to_sentence(['one', 'two', 'three'], last_word_connector: ' and ') + assert_equal "one two, and three", to_sentence(["one", "two", "three"], words_connector: " ") + assert_equal "one & two, and three", to_sentence(["one", "two", "three"], words_connector: " & ".html_safe) + assert_equal "onetwo, and three", to_sentence(["one", "two", "three"], words_connector: nil) + assert_equal "one, two, and also three", to_sentence(["one", "two", "three"], last_word_connector: ", and also ") + assert_equal "one, twothree", to_sentence(["one", "two", "three"], last_word_connector: nil) + assert_equal "one, two three", to_sentence(["one", "two", "three"], last_word_connector: " ") + assert_equal "one, two and three", to_sentence(["one", "two", "three"], last_word_connector: " and ") + end + + test "to_sentence is not affected by $," do + separator_was = $, + $, = "|" + begin + assert_equal "one and two", to_sentence(["one", "two"]) + assert_equal "one, two, and three", to_sentence(["one", "two", "three"]) + ensure + $, = separator_was + end end end diff --git a/actionview/test/template/partial_iteration_test.rb b/actionview/test/template/partial_iteration_test.rb index 695f9f1bef..06bbdabac0 100644 --- a/actionview/test/template/partial_iteration_test.rb +++ b/actionview/test/template/partial_iteration_test.rb @@ -1,5 +1,7 @@ -require 'abstract_unit' -require 'action_view/renderer/partial_renderer' +# frozen_string_literal: true + +require "abstract_unit" +require "action_view/renderer/partial_renderer" class PartialIterationTest < ActiveSupport::TestCase def test_has_size_and_index diff --git a/actionview/test/template/record_identifier_test.rb b/actionview/test/template/record_identifier_test.rb index 04898c0b0e..29012e943d 100644 --- a/actionview/test/template/record_identifier_test.rb +++ b/actionview/test/template/record_identifier_test.rb @@ -1,5 +1,7 @@ -require 'abstract_unit' -require 'controller/fake_models' +# frozen_string_literal: true + +require "abstract_unit" +require "controller/fake_models" class RecordIdentifierTest < ActiveSupport::TestCase include ActionView::RecordIdentifier @@ -7,8 +9,8 @@ class RecordIdentifierTest < ActiveSupport::TestCase def setup @klass = Comment @record = @klass.new - @singular = 'comment' - @plural = 'comments' + @singular = "comment" + @plural = "comments" end def test_dom_id_with_new_record @@ -73,7 +75,7 @@ class RecordIdentifierWithoutActiveModelTest < ActiveSupport::TestCase end def test_dom_class - assert_equal 'airplane', dom_class(@record) + assert_equal "airplane", dom_class(@record) end def test_dom_class_with_prefix @@ -86,6 +88,6 @@ class RecordIdentifierWithoutActiveModelTest < ActiveSupport::TestCase end def test_dom_class_as_singleton_method - assert_equal 'airplane', ActionView::RecordIdentifier.dom_class(@record) + 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 bfc5d04bed..7bbbfccdd0 100644 --- a/actionview/test/template/record_tag_helper_test.rb +++ b/actionview/test/template/record_tag_helper_test.rb @@ -1,4 +1,6 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class RecordTagPost extend ActiveModel::Naming @@ -14,7 +16,6 @@ class RecordTagPost end class RecordTagHelperTest < ActionView::TestCase - tests ActionView::Helpers::RecordTagHelper def setup diff --git a/actionview/test/template/render_test.rb b/actionview/test/template/render_test.rb index ad93236d32..8782eb4430 100644 --- a/actionview/test/template/render_test.rb +++ b/actionview/test/template/render_test.rb @@ -1,25 +1,27 @@ -require 'abstract_unit' -require 'controller/fake_models' +# frozen_string_literal: true + +require "abstract_unit" +require "controller/fake_models" class TestController < ActionController::Base end module RenderTestCases def setup_view(paths) - @assigns = { :secret => 'in the sauce' } + @assigns = { secret: "in the sauce" } @view = Class.new(ActionView::Base) do def view_cache_dependencies; end - def fragment_cache_key(key) - ActiveSupport::Cache.expand_cache_key(key, :views) + def combined_fragment_cache_key(key) + [ :views, key ] end end.new(paths, @assigns) @controller_view = TestController.new.view_context # Reload and register danish language for testing - I18n.backend.store_translations 'da', {} - I18n.backend.store_translations 'pt-BR', {} + I18n.backend.store_translations "da", {} + 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(&:to_s).sort @@ -27,121 +29,132 @@ module RenderTestCases def test_render_without_options e = assert_raises(ArgumentError) { @view.render() } - assert_match(/You invoked render but did not give any of (.+) option./, e.message) + assert_match(/You invoked render but did not give any of (.+) option\./, e.message) end def test_render_file - assert_equal "Hello world!", @view.render(:file => "test/hello_world") + assert_equal "Hello world!", @view.render(file: "test/hello_world") end # Test if :formats, :locale etc. options are passed correctly to the resolvers. def test_render_file_with_format - assert_match "<h1>No Comment</h1>", @view.render(:file => "comments/empty", :formats => [:html]) - assert_match "<error>No Comment</error>", @view.render(:file => "comments/empty", :formats => [:xml]) - assert_match "<error>No Comment</error>", @view.render(:file => "comments/empty", :formats => :xml) + assert_match "<h1>No Comment</h1>", @view.render(file: "comments/empty", formats: [:html]) + assert_match "<error>No Comment</error>", @view.render(file: "comments/empty", formats: [:xml]) + assert_match "<error>No Comment</error>", @view.render(file: "comments/empty", formats: :xml) end def test_render_template_with_format - assert_match "<h1>No Comment</h1>", @view.render(:template => "comments/empty", :formats => [:html]) - assert_match "<error>No Comment</error>", @view.render(:template => "comments/empty", :formats => [:xml]) + assert_match "<h1>No Comment</h1>", @view.render(template: "comments/empty", formats: [:html]) + assert_match "<error>No Comment</error>", @view.render(template: "comments/empty", formats: [:xml]) end def test_rendered_format_without_format - @view.render(:inline => "test") + @view.render(inline: "test") assert_equal :html, @view.lookup_context.rendered_format end def test_render_partial_implicitly_use_format_of_the_rendered_template @view.lookup_context.formats = [:json] - assert_equal "Hello world", @view.render(:template => "test/one", :formats => [:html]) + assert_equal "Hello world", @view.render(template: "test/one", formats: [:html]) end def test_render_partial_implicitly_use_format_of_the_rendered_partial @view.lookup_context.formats = [:html] - assert_equal "Third level", @view.render(:template => "test/html_template") + assert_equal "Third level", @view.render(template: "test/html_template") end def test_render_partial_use_last_prepended_format_for_partials_with_the_same_names @view.lookup_context.formats = [:html] - assert_equal "\nHTML Template, but JSON partial", @view.render(:template => "test/change_priority") + assert_equal "\nHTML Template, but JSON partial", @view.render(template: "test/change_priority") end def test_render_template_with_a_missing_partial_of_another_format @view.lookup_context.formats = [:html] e = assert_raise ActionView::Template::Error do - @view.render(:template => "with_format", :formats => [:json]) + @view.render(template: "with_format", formats: [:json]) end assert_includes(e.message, "Missing partial /_missing with {:locale=>[:en], :formats=>[:json], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby]}.") end def test_render_file_with_locale - assert_equal "<h1>Kein Kommentar</h1>", @view.render(:file => "comments/empty", :locale => [:de]) - assert_equal "<h1>Kein Kommentar</h1>", @view.render(:file => "comments/empty", :locale => :de) + assert_equal "<h1>Kein Kommentar</h1>", @view.render(file: "comments/empty", locale: [:de]) + assert_equal "<h1>Kein Kommentar</h1>", @view.render(file: "comments/empty", locale: :de) end def test_render_template_with_locale - assert_equal "<h1>Kein Kommentar</h1>", @view.render(:template => "comments/empty", :locale => [:de]) + assert_equal "<h1>Kein Kommentar</h1>", @view.render(template: "comments/empty", locale: [:de]) + end + + def test_render_template_with_variants + assert_equal "<h1>No Comment</h1>\n", @view.render(template: "comments/empty", variants: :grid) end def test_render_file_with_handlers - assert_equal "<h1>No Comment</h1>\n", @view.render(:file => "comments/empty", :handlers => [:builder]) - assert_equal "<h1>No Comment</h1>\n", @view.render(:file => "comments/empty", :handlers => :builder) + assert_equal "<h1>No Comment</h1>\n", @view.render(file: "comments/empty", handlers: [:builder]) + assert_equal "<h1>No Comment</h1>\n", @view.render(file: "comments/empty", handlers: :builder) end def test_render_template_with_handlers - assert_equal "<h1>No Comment</h1>\n", @view.render(:template => "comments/empty", :handlers => [:builder]) + assert_equal "<h1>No Comment</h1>\n", @view.render(template: "comments/empty", handlers: [:builder]) end def test_render_raw_template_with_handlers - assert_equal "<%= hello_world %>\n", @view.render(:template => "plain_text") + assert_equal "<%= hello_world %>\n", @view.render(template: "plain_text") end def test_render_raw_template_with_quotes - assert_equal %q;Here are some characters: !@#$%^&*()-="'}{`; + "\n", @view.render(:template => "plain_text_with_characters") + assert_equal %q;Here are some characters: !@#$%^&*()-="'}{`; + "\n", @view.render(template: "plain_text_with_characters") + end + + def test_render_raw_is_html_safe_and_does_not_escape_output + buffer = ActiveSupport::SafeBuffer.new + buffer << @view.render(file: "plain_text") + assert_equal true, buffer.html_safe? + assert_equal buffer, "<%= hello_world %>\n" end def test_render_ruby_template_with_handlers - assert_equal "Hello from Ruby code", @view.render(:template => "ruby_template") + assert_equal "Hello from Ruby code", @view.render(template: "ruby_template") end def test_render_ruby_template_inline - assert_equal '4', @view.render(:inline => "(2**2).to_s", :type => :ruby) + assert_equal "4", @view.render(inline: "(2**2).to_s", type: :ruby) end def test_render_file_with_localization_on_context_level old_locale, @view.locale = @view.locale, :da - assert_equal "Hey verden", @view.render(:file => "test/hello_world") + assert_equal "Hey verden", @view.render(file: "test/hello_world") ensure @view.locale = old_locale end def test_render_file_with_dashed_locale old_locale, @view.locale = @view.locale, :"pt-BR" - assert_equal "Ola mundo", @view.render(:file => "test/hello_world") + assert_equal "Ola mundo", @view.render(file: "test/hello_world") ensure @view.locale = old_locale end def test_render_file_at_top_level - assert_equal 'Elastica', @view.render(:file => '/shared') + assert_equal "Elastica", @view.render(file: "/shared") end def test_render_file_with_full_path - template_path = File.join(File.dirname(__FILE__), '../fixtures/test/hello_world') - assert_equal "Hello world!", @view.render(:file => template_path) + template_path = File.expand_path("../fixtures/test/hello_world", __dir__) + assert_equal "Hello world!", @view.render(file: template_path) end def test_render_file_with_instance_variables - assert_equal "The secret is in the sauce\n", @view.render(:file => "test/render_file_with_ivar") + assert_equal "The secret is in the sauce\n", @view.render(file: "test/render_file_with_ivar") end def test_render_file_with_locals - locals = { :secret => 'in the sauce' } - assert_equal "The secret is in the sauce\n", @view.render(:file => "test/render_file_with_locals", :locals => locals) + locals = { secret: "in the sauce" } + assert_equal "The secret is in the sauce\n", @view.render(file: "test/render_file_with_locals", locals: locals) end def test_render_file_not_using_full_path_with_dot_in_path - assert_equal "The secret is in the sauce\n", @view.render(:file => "test/dot.directory/render_file_with_ivar") + assert_equal "The secret is in the sauce\n", @view.render(file: "test/dot.directory/render_file_with_ivar") end def test_render_partial_from_default @@ -149,84 +162,88 @@ module RenderTestCases end def test_render_outside_path - assert File.exist?(File.join(File.dirname(__FILE__), '../../test/abstract_unit.rb')) + assert File.exist?(File.expand_path("../../test/abstract_unit.rb", __dir__)) assert_raises ActionView::MissingTemplate do - @view.render(:template => "../\\../test/abstract_unit.rb") + @view.render(template: "../\\../test/abstract_unit.rb") end end def test_render_partial - assert_equal "only partial", @view.render(:partial => "test/partial_only") + assert_equal "only partial", @view.render(partial: "test/partial_only") end def test_render_partial_with_format - assert_equal 'partial html', @view.render(:partial => 'test/partial') + assert_equal "partial html", @view.render(partial: "test/partial") + end + + def test_render_partial_with_variants + assert_equal "<h1>Partial with variants</h1>\n", @view.render(partial: "test/partial_with_variants", variants: :grid) end def test_render_partial_with_selected_format - assert_equal 'partial html', @view.render(:partial => 'test/partial', :formats => :html) - assert_equal 'partial js', @view.render(:partial => 'test/partial', :formats => [:js]) + assert_equal "partial html", @view.render(partial: "test/partial", formats: :html) + assert_equal "partial js", @view.render(partial: "test/partial", formats: [:js]) end def test_render_partial_at_top_level # file fixtures/_top_level_partial_only (not fixtures/test) - assert_equal 'top level partial', @view.render(:partial => '/top_level_partial_only') + assert_equal "top level partial", @view.render(partial: "/top_level_partial_only") end def test_render_partial_with_format_at_top_level # file fixtures/_top_level_partial.html (not fixtures/test, with format extension) - assert_equal 'top level partial html', @view.render(:partial => '/top_level_partial') + assert_equal "top level partial html", @view.render(partial: "/top_level_partial") end def test_render_partial_with_locals - assert_equal "5", @view.render(:partial => "test/counter", :locals => { :counter_counter => 5 }) + assert_equal "5", @view.render(partial: "test/counter", locals: { counter_counter: 5 }) end def test_render_partial_with_locals_from_default - assert_equal "only partial", @view.render("test/partial_only", :counter_counter => 5) + assert_equal "only partial", @view.render("test/partial_only", counter_counter: 5) end def test_render_partial_with_number - assert_nothing_raised { @view.render(:partial => "test/200") } + assert_nothing_raised { @view.render(partial: "test/200") } end def test_render_partial_with_missing_filename - assert_raises(ActionView::MissingTemplate) { @view.render(:partial => "test/") } + assert_raises(ActionView::MissingTemplate) { @view.render(partial: "test/") } end def test_render_partial_with_incompatible_object - e = assert_raises(ArgumentError) { @view.render(:partial => nil) } + e = assert_raises(ArgumentError) { @view.render(partial: nil) } 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') } + assert_nothing_raised { @view.render(partial: "test/FooBar") } end def test_render_partial_with_hyphen - assert_nothing_raised { @view.render(:partial => "test/a-in") } + assert_nothing_raised { @view.render(partial: "test/a-in") } end def test_render_partial_with_unicode_text - assert_nothing_raised { @view.render(:partial => "test/🍣") } + assert_nothing_raised { @view.render(partial: "test/🍣") } 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, " + + 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, " + + 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 def test_render_partial_with_errors - e = assert_raises(ActionView::Template::Error) { @view.render(:partial => "test/raise") } + e = assert_raises(ActionView::Template::Error) { @view.render(partial: "test/raise") } assert_match %r!method.*doesnt_exist!, e.message assert_equal "", e.sub_template_message assert_equal "1", e.line_number @@ -235,7 +252,7 @@ module RenderTestCases end def test_render_error_indentation - e = assert_raises(ActionView::Template::Error) { @view.render(:partial => "test/raise_indentation") } + e = assert_raises(ActionView::Template::Error) { @view.render(partial: "test/raise_indentation") } error_lines = e.annoted_source_code assert_match %r!error\shere!, e.message assert_equal "11", e.line_number @@ -244,15 +261,15 @@ module RenderTestCases end def test_render_sub_template_with_errors - e = assert_raises(ActionView::Template::Error) { @view.render(:template => "test/sub_template_raise") } + e = assert_raises(ActionView::Template::Error) { @view.render(template: "test/sub_template_raise") } assert_match %r!method.*doesnt_exist!, e.message - assert_equal "Trace of template inclusion: #{File.expand_path("#{FIXTURE_LOAD_PATH}/test/sub_template_raise.html.erb")}", e.sub_template_message + assert_match %r{Trace of template inclusion: .*test/sub_template_raise\.html\.erb}, e.sub_template_message assert_equal "1", e.line_number assert_equal File.expand_path("#{FIXTURE_LOAD_PATH}/test/_raise.html.erb"), e.file_name end def test_render_file_with_errors - e = assert_raises(ActionView::Template::Error) { @view.render(:file => File.expand_path("test/_raise", FIXTURE_LOAD_PATH)) } + e = assert_raises(ActionView::Template::Error) { @view.render(file: File.expand_path("test/_raise", FIXTURE_LOAD_PATH)) } assert_match %r!method.*doesnt_exist!, e.message assert_equal "", e.sub_template_message assert_equal "1", e.line_number @@ -261,109 +278,126 @@ module RenderTestCases end def test_render_object - assert_equal "Hello: david", @view.render(:partial => "test/customer", :object => Customer.new("david")) - assert_equal "FalseClass", @view.render(:partial => "test/klass", :object => false) - assert_equal "NilClass", @view.render(:partial => "test/klass", :object => nil) + assert_equal "Hello: david", @view.render(partial: "test/customer", object: Customer.new("david")) + assert_equal "FalseClass", @view.render(partial: "test/klass", object: false) + assert_equal "NilClass", @view.render(partial: "test/klass", object: nil) end def test_render_object_with_array - assert_equal "[1, 2, 3]", @view.render(:partial => "test/object_inspector", :object => [1, 2, 3]) + assert_equal "[1, 2, 3]", @view.render(partial: "test/object_inspector", object: [1, 2, 3]) end def test_render_partial_collection - assert_equal "Hello: davidHello: mary", @view.render(:partial => "test/customer", :collection => [ Customer.new("david"), Customer.new("mary") ]) + assert_equal "Hello: davidHello: mary", @view.render(partial: "test/customer", collection: [ Customer.new("david"), Customer.new("mary") ]) end def test_render_partial_collection_with_partial_name_containing_dot assert_equal "Hello: davidHello: mary", - @view.render(:partial => "test/customer.mobile", :collection => [ Customer.new("david"), Customer.new("mary") ]) + @view.render(partial: "test/customer.mobile", collection: [ Customer.new("david"), Customer.new("mary") ]) end def test_render_partial_collection_as_by_string assert_equal "david david davidmary mary mary", - @view.render(:partial => "test/customer_with_var", :collection => [ Customer.new("david"), Customer.new("mary") ], :as => 'customer') + @view.render(partial: "test/customer_with_var", collection: [ Customer.new("david"), Customer.new("mary") ], as: "customer") end def test_render_partial_collection_as_by_symbol assert_equal "david david davidmary mary mary", - @view.render(:partial => "test/customer_with_var", :collection => [ Customer.new("david"), Customer.new("mary") ], :as => :customer) + @view.render(partial: "test/customer_with_var", collection: [ Customer.new("david"), Customer.new("mary") ], as: :customer) end def test_render_partial_collection_without_as assert_equal "local_inspector,local_inspector_counter,local_inspector_iteration", - @view.render(:partial => "test/local_inspector", :collection => [ Customer.new("mary") ]) + @view.render(partial: "test/local_inspector", collection: [ Customer.new("mary") ]) + end + + def test_render_partial_collection_with_different_partials_still_provides_partial_iteration + a = {} + b = {} + def a.to_partial_path; "test/partial_iteration_1"; end + def b.to_partial_path; "test/partial_iteration_2"; end + + assert_equal "local-variable\nlocal-variable", @controller_view.render([a, b]) end def test_render_partial_with_empty_collection_should_return_nil - assert_nil @view.render(:partial => "test/customer", :collection => []) + assert_nil @view.render(partial: "test/customer", collection: []) end def test_render_partial_with_nil_collection_should_return_nil - assert_nil @view.render(:partial => "test/customer", :collection => nil) + assert_nil @view.render(partial: "test/customer", collection: nil) + end + + def test_render_partial_collection_for_non_array + customers = Enumerator.new do |y| + y.yield(Customer.new("david")) + y.yield(Customer.new("mary")) + end + assert_equal "Hello: davidHello: mary", @view.render(partial: "test/customer", collection: customers) 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') + 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) + 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 ]) + assert_equal "Hello: davidHello: Anonymous", @view.render(partial: "test/customer", collection: [ Customer.new("david"), nil ]) end def test_render_partial_with_layout_using_collection_and_template - assert_equal "<b>Hello: Amazon</b><b>Hello: Yahoo</b>", @view.render(:partial => "test/customer", :layout => 'test/b_layout_for_partial', :collection => [ Customer.new("Amazon"), Customer.new("Yahoo") ]) + assert_equal "<b>Hello: Amazon</b><b>Hello: Yahoo</b>", @view.render(partial: "test/customer", layout: "test/b_layout_for_partial", collection: [ Customer.new("Amazon"), Customer.new("Yahoo") ]) end def test_render_partial_with_layout_using_collection_and_template_makes_current_item_available_in_layout assert_equal '<b class="amazon">Hello: Amazon</b><b class="yahoo">Hello: Yahoo</b>', - @view.render(:partial => "test/customer", :layout => 'test/b_layout_for_partial_with_object', :collection => [ Customer.new("Amazon"), Customer.new("Yahoo") ]) + @view.render(partial: "test/customer", layout: "test/b_layout_for_partial_with_object", collection: [ Customer.new("Amazon"), Customer.new("Yahoo") ]) end def test_render_partial_with_layout_using_collection_and_template_makes_current_item_counter_available_in_layout assert_equal '<b data-counter="0">Hello: Amazon</b><b data-counter="1">Hello: Yahoo</b>', - @view.render(:partial => "test/customer", :layout => 'test/b_layout_for_partial_with_object_counter', :collection => [ Customer.new("Amazon"), Customer.new("Yahoo") ]) + @view.render(partial: "test/customer", layout: "test/b_layout_for_partial_with_object_counter", collection: [ Customer.new("Amazon"), Customer.new("Yahoo") ]) end def test_render_partial_with_layout_using_object_and_template_makes_object_available_in_layout assert_equal '<b class="amazon">Hello: Amazon</b>', - @view.render(:partial => "test/customer", :layout => 'test/b_layout_for_partial_with_object', :object => Customer.new("Amazon")) + @view.render(partial: "test/customer", layout: "test/b_layout_for_partial_with_object", object: Customer.new("Amazon")) end def test_render_partial_with_empty_array_should_return_nil - assert_nil @view.render(:partial => []) + assert_nil @view.render(partial: []) end def test_render_partial_using_string - assert_equal "Hello: Anonymous", @controller_view.render('customer') + assert_equal "Hello: Anonymous", @controller_view.render("customer") end def test_render_partial_with_locals_using_string - assert_equal "Hola: david", @controller_view.render('customer_greeting', :greeting => 'Hola', :customer_greeting => Customer.new("david")) + assert_equal "Hola: david", @controller_view.render("customer_greeting", greeting: "Hola", customer_greeting: Customer.new("david")) end def test_render_partial_with_object_uses_render_partial_path assert_equal "Hello: lifo", - @controller_view.render(:partial => Customer.new("lifo"), :locals => {:greeting => "Hello"}) + @controller_view.render(partial: Customer.new("lifo"), locals: { greeting: "Hello" }) end def test_render_partial_with_object_and_format_uses_render_partial_path assert_equal "<greeting>Hello</greeting><name>lifo</name>", - @controller_view.render(:partial => Customer.new("lifo"), :formats => :xml, :locals => {:greeting => "Hello"}) + @controller_view.render(partial: Customer.new("lifo"), formats: :xml, locals: { greeting: "Hello" }) end def test_render_partial_using_object assert_equal "Hello: lifo", - @controller_view.render(Customer.new("lifo"), :greeting => "Hello") + @controller_view.render(Customer.new("lifo"), greeting: "Hello") end def test_render_partial_using_collection customers = [ Customer.new("Amazon"), Customer.new("Yahoo") ] assert_equal "Hello: AmazonHello: Yahoo", - @controller_view.render(customers, :greeting => "Hello") + @controller_view.render(customers, greeting: "Hello") end def test_render_partial_using_collection_without_path @@ -378,44 +412,42 @@ module RenderTestCases assert_equal :partial_name_local_variable, exception.cause.name end - # TODO: The reason for this test is unclear, improve documentation - def test_render_partial_and_fallback_to_layout - assert_equal "Before (Josh)\n\nAfter", @view.render(:partial => "test/layout_for_partial", :locals => { :name => "Josh" }) + def test_render_partial_with_no_block_given_to_yield + assert_equal "Before (Josh)\n\nAfter", @view.render(partial: "test/layout_for_partial", locals: { name: "Josh" }) end - # TODO: The reason for this test is unclear, improve documentation - def test_render_missing_xml_partial_and_raise_missing_template + def test_render_partial_with_non_existent_format_and_raise_missing_template @view.formats = [:xml] - assert_raises(ActionView::MissingTemplate) { @view.render(:partial => "test/layout_for_partial") } + assert_raises(ActionView::MissingTemplate) { @view.render(partial: "test/layout_for_partial") } ensure @view.formats = nil end def test_render_layout_with_block_and_other_partial_inside - render = @view.render(:layout => "test/layout_with_partial_and_yield") { "Yield!" } + render = @view.render(layout: "test/layout_with_partial_and_yield") { "Yield!" } assert_equal "Before\npartial html\nYield!\nAfter\n", render end def test_render_inline - assert_equal "Hello, World!", @view.render(:inline => "Hello, World!") + assert_equal "Hello, World!", @view.render(inline: "Hello, World!") end def test_render_inline_with_locals - assert_equal "Hello, Josh!", @view.render(:inline => "Hello, <%= name %>!", :locals => { :name => "Josh" }) + assert_equal "Hello, Josh!", @view.render(inline: "Hello, <%= name %>!", locals: { name: "Josh" }) end def test_render_fallbacks_to_erb_for_unknown_types - assert_equal "Hello, World!", @view.render(:inline => "Hello, World!", :type => :bar) + assert_equal "Hello, World!", @view.render(inline: "Hello, World!", type: :bar) end CustomHandler = lambda do |template| - "@output_buffer = ''\n" + + "@output_buffer = ''.dup\n" \ "@output_buffer << 'source: #{template.source.inspect}'\n" end def test_render_inline_with_render_from_to_proc ActionView::Template.register_template_handler :ruby_handler, :source.to_proc - assert_equal '3', @view.render(inline: "(1 + 2).to_s", type: :ruby_handler) + assert_equal "3", @view.render(inline: "(1 + 2).to_s", type: :ruby_handler) ensure ActionView::Template.unregister_template_handler :ruby_handler end @@ -435,17 +467,17 @@ module RenderTestCases end def test_render_body - assert_equal 'some body', @view.render(body: 'some body') + assert_equal "some body", @view.render(body: "some body") end def test_render_plain - assert_equal 'some plaintext', @view.render(plain: 'some plaintext') + assert_equal "some plaintext", @view.render(plain: "some plaintext") end def test_render_knows_about_types_registered_when_extensions_are_checked_earlier_in_initialization ActionView::Template::Handlers.extensions ActionView::Template.register_template_handler :foo, CustomHandler - assert ActionView::Template::Handlers.extensions.include?(:foo) + assert_includes ActionView::Template::Handlers.extensions, :foo ensure ActionView::Template.unregister_template_handler :foo end @@ -460,57 +492,55 @@ module RenderTestCases end def test_render_ignores_templates_with_malformed_template_handlers - ActiveSupport::Deprecation.silence do - %w(malformed malformed.erb malformed.html.erb malformed.en.html.erb).each do |name| - assert File.exist?(File.expand_path("#{FIXTURE_LOAD_PATH}/test/malformed/#{name}~")), "Malformed file (#{name}~) which should be ignored does not exists" - assert_raises(ActionView::MissingTemplate) { @view.render(:file => "test/malformed/#{name}") } - end + %w(malformed malformed.erb malformed.html.erb malformed.en.html.erb).each do |name| + assert File.exist?(File.expand_path("#{FIXTURE_LOAD_PATH}/test/malformed/#{name}~")), "Malformed file (#{name}~) which should be ignored does not exists" + assert_raises(ActionView::MissingTemplate) { @view.render(file: "test/malformed/#{name}") } end end def test_render_with_layout assert_equal %(<title></title>\nHello world!\n), - @view.render(:file => "test/hello_world", :layout => "layouts/yield") + @view.render(file: "test/hello_world", layout: "layouts/yield") end def test_render_with_layout_which_has_render_inline assert_equal %(welcome\nHello world!\n), - @view.render(:file => "test/hello_world", :layout => "layouts/yield_with_render_inline_inside") + @view.render(file: "test/hello_world", layout: "layouts/yield_with_render_inline_inside") end def test_render_with_layout_which_renders_another_partial assert_equal %(partial html\nHello world!\n), - @view.render(:file => "test/hello_world", :layout => "layouts/yield_with_render_partial_inside") + @view.render(file: "test/hello_world", layout: "layouts/yield_with_render_partial_inside") end def test_render_partial_with_html_only_extension assert_equal %(<h1>partial html</h1>\nHello world!\n), - @view.render(:file => "test/hello_world", :layout => "layouts/render_partial_html") + @view.render(file: "test/hello_world", layout: "layouts/render_partial_html") end def test_render_layout_with_block_and_yield assert_equal %(Content from block!\n), - @view.render(:layout => "layouts/yield_only") { "Content from block!" } + @view.render(layout: "layouts/yield_only") { "Content from block!" } end def test_render_layout_with_block_and_yield_with_params assert_equal %(Yield! Content from block!\n), - @view.render(:layout => "layouts/yield_with_params") { |param| "#{param} Content from block!" } + @view.render(layout: "layouts/yield_with_params") { |param| "#{param} Content from block!" } end def test_render_layout_with_block_which_renders_another_partial_and_yields assert_equal %(partial html\nContent from block!\n), - @view.render(:layout => "layouts/partial_and_yield") { "Content from block!" } + @view.render(layout: "layouts/partial_and_yield") { "Content from block!" } end def test_render_partial_and_layout_without_block_with_locals assert_equal %(Before (Foo!)\npartial html\nAfter), - @view.render(:partial => 'test/partial', :layout => 'test/layout_for_partial', :locals => { :name => 'Foo!'}) + @view.render(partial: "test/partial", layout: "test/layout_for_partial", locals: { name: "Foo!" }) end def test_render_partial_and_layout_without_block_with_locals_and_rendering_another_partial assert_equal %(Before (Foo!)\npartial html\npartial with partial\n\nAfter), - @view.render(:partial => 'test/partial_with_partial', :layout => 'test/layout_for_partial', :locals => { :name => 'Foo!'}) + @view.render(partial: "test/partial_with_partial", layout: "test/layout_for_partial", locals: { name: "Foo!" }) end def test_render_partial_shortcut_with_block_content @@ -520,42 +550,42 @@ module RenderTestCases 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!'}) + @view.render(partial: "test/partial_with_layout", layout: "test/layout_for_partial", locals: { name: "Foo!" }) end def test_render_layout_with_a_nested_render_layout_call_using_block_with_render_partial assert_equal %(Before (Foo!)\nBefore (Bar!)\n\n partial html\n\nAfterpartial with layout\n\nAfter), - @view.render(:partial => 'test/partial_with_layout_block_partial', :layout => 'test/layout_for_partial', :locals => { :name => 'Foo!'}) + @view.render(partial: "test/partial_with_layout_block_partial", layout: "test/layout_for_partial", locals: { name: "Foo!" }) end def test_render_layout_with_a_nested_render_layout_call_using_block_with_render_content assert_equal %(Before (Foo!)\nBefore (Bar!)\n\n Content from inside layout!\n\nAfterpartial with layout\n\nAfter), - @view.render(:partial => 'test/partial_with_layout_block_content', :layout => 'test/layout_for_partial', :locals => { :name => 'Foo!'}) + @view.render(partial: "test/partial_with_layout_block_content", layout: "test/layout_for_partial", locals: { name: "Foo!" }) end def test_render_partial_with_layout_raises_descriptive_error - e = assert_raises(ActionView::MissingTemplate) { @view.render(partial: 'test/partial', layout: true) } + e = assert_raises(ActionView::MissingTemplate) { @view.render(partial: "test/partial", layout: true) } assert_match "Missing partial /_true with", e.message end def test_render_with_nested_layout assert_equal %(<title>title</title>\n\n<div id="column">column</div>\n<div id="content">content</div>\n), - @view.render(:file => "test/nested_layout", :layout => "layouts/yield") + @view.render(file: "test/nested_layout", layout: "layouts/yield") end def test_render_with_file_in_layout assert_equal %(\n<title>title</title>\n\n), - @view.render(:file => "test/layout_render_file") + @view.render(file: "test/layout_render_file") end def test_render_layout_with_object assert_equal %(<title>David</title>), - @view.render(:file => "test/layout_render_object") + @view.render(file: "test/layout_render_object") end def test_render_with_passing_couple_extensions_to_one_register_template_handler_function_call ActionView::Template.register_template_handler :foo1, :foo2, CustomHandler - assert_equal @view.render(inline: "Hello, World!", type: :foo1), @view.render(inline: "Hello, World!", type: :foo2) + assert_equal @view.render(inline: "Hello, World!".dup, type: :foo1), @view.render(inline: "Hello, World!".dup, type: :foo2) ensure ActionView::Template.unregister_template_handler :foo1, :foo2 end @@ -600,7 +630,7 @@ class LazyViewRenderTest < ActiveSupport::TestCase def test_render_utf8_template_with_magic_comment with_external_encoding Encoding::ASCII_8BIT do - result = @view.render(:file => "test/utf8_magic", :formats => [:html], :layouts => "layouts/yield") + result = @view.render(file: "test/utf8_magic", formats: [:html], layouts: "layouts/yield") assert_equal Encoding::UTF_8, result.encoding assert_equal "\nРусский \nтекст\n\nUTF-8\nUTF-8\nUTF-8\n", result end @@ -608,7 +638,7 @@ class LazyViewRenderTest < ActiveSupport::TestCase def test_render_utf8_template_with_default_external_encoding with_external_encoding Encoding::UTF_8 do - result = @view.render(:file => "test/utf8", :formats => [:html], :layouts => "layouts/yield") + result = @view.render(file: "test/utf8", formats: [:html], layouts: "layouts/yield") assert_equal Encoding::UTF_8, result.encoding assert_equal "Русский текст\n\nUTF-8\nUTF-8\nUTF-8\n", result end @@ -616,15 +646,15 @@ class LazyViewRenderTest < ActiveSupport::TestCase def test_render_utf8_template_with_incompatible_external_encoding with_external_encoding Encoding::SHIFT_JIS do - e = assert_raises(ActionView::Template::Error) { @view.render(:file => "test/utf8", :formats => [:html], :layouts => "layouts/yield") } - assert_match 'Your template was not saved as valid Shift_JIS', e.cause.message + e = assert_raises(ActionView::Template::Error) { @view.render(file: "test/utf8", formats: [:html], layouts: "layouts/yield") } + assert_match "Your template was not saved as valid Shift_JIS", e.cause.message end end def test_render_utf8_template_with_partial_with_incompatible_encoding with_external_encoding Encoding::SHIFT_JIS do - e = assert_raises(ActionView::Template::Error) { @view.render(:file => "test/utf8_magic_with_bare_partial", :formats => [:html], :layouts => "layouts/yield") } - assert_match 'Your template was not saved as valid Shift_JIS', e.cause.message + e = assert_raises(ActionView::Template::Error) { @view.render(file: "test/utf8_magic_with_bare_partial", formats: [:html], layouts: "layouts/yield") } + assert_match "Your template was not saved as valid Shift_JIS", e.cause.message end end @@ -661,7 +691,7 @@ class CachedCollectionViewRenderTest < ActiveSupport::TestCase customer = Customer.new("david", 1) key = cache_key(customer, "test/_customer") - ActionView::PartialRenderer.collection_cache.write(key, 'Cached') + ActionView::PartialRenderer.collection_cache.write(key, "Cached") assert_not_equal "Cached", @view.render(partial: "test/customer", collection: [customer]) @@ -671,7 +701,7 @@ class CachedCollectionViewRenderTest < ActiveSupport::TestCase customer = Customer.new("david", 1) key = cache_key(customer, "test/_customer") - ActionView::PartialRenderer.collection_cache.write(key, 'Cached') + ActionView::PartialRenderer.collection_cache.write(key, "Cached") assert_equal "Cached", @view.render(partial: "test/customer", collection: [customer], cached: true) @@ -681,7 +711,7 @@ class CachedCollectionViewRenderTest < ActiveSupport::TestCase customer = CachedCustomer.new("david", 1) key = cache_key(customer, "test/_cached_customer") - ActionView::PartialRenderer.collection_cache.write(key, 'Cached') + ActionView::PartialRenderer.collection_cache.write(key, "Cached") assert_equal "Cached", @view.render(partial: "test/cached_customer", collection: [customer], cached: true) @@ -690,6 +720,6 @@ class CachedCollectionViewRenderTest < ActiveSupport::TestCase private def cache_key(*names, virtual_path) digest = ActionView::Digestor.digest name: virtual_path, finder: @view.lookup_context, dependencies: [] - @view.fragment_cache_key([ *names, digest ]) + @view.combined_fragment_cache_key([ "#{virtual_path}:#{digest}", *names ]) end end diff --git a/actionview/test/template/resolver_cache_test.rb b/actionview/test/template/resolver_cache_test.rb index 1081c13db0..8a5db1346a 100644 --- a/actionview/test/template/resolver_cache_test.rb +++ b/actionview/test/template/resolver_cache_test.rb @@ -1,4 +1,6 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class ResolverCacheTest < ActiveSupport::TestCase def test_inspect_shields_cache_internals diff --git a/actionview/test/template/resolver_patterns_test.rb b/actionview/test/template/resolver_patterns_test.rb index 1a091bd692..1e1a4c5063 100644 --- a/actionview/test/template/resolver_patterns_test.rb +++ b/actionview/test/template/resolver_patterns_test.rb @@ -1,19 +1,21 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class ResolverPatternsTest < ActiveSupport::TestCase def setup - path = File.expand_path("../../fixtures/", __FILE__) + path = File.expand_path("../fixtures", __dir__) pattern = ":prefix/{:formats/,}:action{.:formats,}{+:variants,}{.:handlers,}" @resolver = ActionView::FileSystemResolver.new(path, pattern) end def test_should_return_empty_list_for_unknown_path - templates = @resolver.find_all("unknown", "custom_pattern", false, {locale: [], formats: [:html], variants: [], handlers: [:erb]}) + templates = @resolver.find_all("unknown", "custom_pattern", false, locale: [], formats: [:html], variants: [], handlers: [:erb]) assert_equal [], templates, "expected an empty list of templates" end def test_should_return_template_for_declared_path - templates = @resolver.find_all("path", "custom_pattern", false, {locale: [], formats: [:html], variants: [], handlers: [:erb]}) + templates = @resolver.find_all("path", "custom_pattern", false, locale: [], formats: [:html], variants: [], handlers: [:erb]) assert_equal 1, templates.size, "expected one template" assert_equal "Hello custom patterns!", templates.first.source assert_equal "custom_pattern/path", templates.first.virtual_path @@ -21,7 +23,7 @@ class ResolverPatternsTest < ActiveSupport::TestCase end def test_should_return_all_templates_when_ambiguous_pattern - templates = @resolver.find_all("another", "custom_pattern", false, {locale: [], formats: [:html], variants: [], handlers: [:erb]}) + templates = @resolver.find_all("another", "custom_pattern", false, locale: [], formats: [:html], variants: [], handlers: [:erb]) assert_equal 2, templates.size, "expected two templates" assert_equal "Another template!", templates[0].source assert_equal "custom_pattern/another", templates[0].virtual_path @@ -30,7 +32,7 @@ class ResolverPatternsTest < ActiveSupport::TestCase end def test_should_return_all_variants_for_any - templates = @resolver.find_all("hello_world", "test", false, {locale: [], formats: [:html, :text], variants: :any, handlers: [:erb]}) + templates = @resolver.find_all("hello_world", "test", false, locale: [], formats: [:html, :text], variants: :any, handlers: [:erb]) assert_equal 3, templates.size, "expected three templates" assert_equal "Hello phone!", templates[0].source assert_equal "test/hello_world", templates[0].virtual_path diff --git a/actionview/test/template/sanitize_helper_test.rb b/actionview/test/template/sanitize_helper_test.rb index efe846a7eb..0e690c82cb 100644 --- a/actionview/test/template/sanitize_helper_test.rb +++ b/actionview/test/template/sanitize_helper_test.rb @@ -1,6 +1,8 @@ -require 'abstract_unit' +# frozen_string_literal: true -# The exhaustive tests are in test/controller/html/sanitizer_test.rb. +require "abstract_unit" + +# The exhaustive tests are in the rails-html-sanitizer gem. # This tests that the helpers hook up correctly to the sanitizer classes. class SanitizeHelperTest < ActionView::TestCase tests ActionView::Helpers::SanitizeHelper @@ -10,22 +12,24 @@ class SanitizeHelperTest < ActionView::TestCase assert_equal "on my mind\nall day long", strip_links("<a href='almost'>on my mind</a>\n<A href='almost'>all day long</A>") assert_equal "Magic", strip_links("<a href='http://www.rubyonrails.com/'>Mag<a href='http://www.ruby-lang.org/'>ic") assert_equal "My mind\nall <b>day</b> long", strip_links("<a href='almost'>My mind</a>\n<A href='almost'>all <b>day</b> long</A>") + assert_equal "<malformed & link", strip_links('<<a href="https://example.org">malformed & link</a>') end def test_sanitize_form - assert_equal '', sanitize("<form action=\"/foo/bar\" method=\"post\"><input></form>") + assert_equal "", sanitize("<form action=\"/foo/bar\" method=\"post\"><input></form>") end def test_should_sanitize_illegal_style_properties raw = %(display:block; position:absolute; left:0; top:0; width:100%; height:100%; z-index:1; background-color:black; background-image:url(http://www.ragingplatypus.com/i/cam-full.jpg); background-x:center; background-y:center; background-repeat:repeat;) - expected = %(display: block; width: 100%; height: 100%; background-color: black; background-x: center; background-y: center;) - assert_equal expected, sanitize_css(raw) + expected = %r(\Adisplay:\s?block;\s?width:\s?100%;\s?height:\s?100%;\s?background-color:\s?black;\s?background-x:\s?center;\s?background-y:\s?center;\z) + assert_match expected, sanitize_css(raw) end def test_strip_tags assert_equal("Dont touch me", strip_tags("Dont touch me")) assert_equal("This is a test.", strip_tags("<p>This <u>is<u> a <a href='test.html'><strong>test</strong></a>.</p>")) assert_equal "This has a here.", strip_tags("This has a <!-- comment --> here.") + assert_equal("Jekyll & Hyde", strip_tags("Jekyll & Hyde")) assert_equal "", strip_tags("<script>") end diff --git a/actionview/test/template/streaming_render_test.rb b/actionview/test/template/streaming_render_test.rb index d06ba4ceb0..ef000300cc 100644 --- a/actionview/test/template/streaming_render_test.rb +++ b/actionview/test/template/streaming_render_test.rb @@ -1,12 +1,14 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class TestController < ActionController::Base end -class FiberedTest < ActiveSupport::TestCase +class SetupFiberedBase < ActiveSupport::TestCase def setup view_paths = ActionController::Base.view_paths - @assigns = { :secret => 'in the sauce', :name => nil } + @assigns = { secret: "in the sauce", name: nil } @view = ActionView::Base.new(view_paths, @assigns) @controller_view = TestController.new.view_context end @@ -17,16 +19,18 @@ class FiberedTest < ActiveSupport::TestCase def buffered_render(options) body = render_body(options) - string = "" + string = "".dup body.each do |piece| string << piece end string end +end +class FiberedTest < SetupFiberedBase def test_streaming_works content = [] - body = render_body(:template => "test/hello_world", :layout => "layouts/yield") + body = render_body(template: "test/hello_world", layout: "layouts/yield") body.each do |piece| content << piece @@ -40,68 +44,68 @@ class FiberedTest < ActiveSupport::TestCase end def test_render_file - assert_equal "Hello world!", buffered_render(:file => "test/hello_world") + assert_equal "Hello world!", buffered_render(file: "test/hello_world") end def test_render_file_with_locals - locals = { :secret => 'in the sauce' } - assert_equal "The secret is in the sauce\n", buffered_render(:file => "test/render_file_with_locals", :locals => locals) + locals = { secret: "in the sauce" } + assert_equal "The secret is in the sauce\n", buffered_render(file: "test/render_file_with_locals", locals: locals) end def test_render_partial - assert_equal "only partial", buffered_render(:partial => "test/partial_only") + assert_equal "only partial", buffered_render(partial: "test/partial_only") end def test_render_inline - assert_equal "Hello, World!", buffered_render(:inline => "Hello, World!") + assert_equal "Hello, World!", buffered_render(inline: "Hello, World!") end def test_render_without_layout - assert_equal "Hello world!", buffered_render(:template => "test/hello_world") + assert_equal "Hello world!", buffered_render(template: "test/hello_world") end def test_render_with_layout assert_equal %(<title></title>\nHello world!\n), - buffered_render(:template => "test/hello_world", :layout => "layouts/yield") + buffered_render(template: "test/hello_world", layout: "layouts/yield") end def test_render_with_layout_which_has_render_inline assert_equal %(welcome\nHello world!\n), - buffered_render(:template => "test/hello_world", :layout => "layouts/yield_with_render_inline_inside") + buffered_render(template: "test/hello_world", layout: "layouts/yield_with_render_inline_inside") end def test_render_with_layout_which_renders_another_partial assert_equal %(partial html\nHello world!\n), - buffered_render(:template => "test/hello_world", :layout => "layouts/yield_with_render_partial_inside") + buffered_render(template: "test/hello_world", layout: "layouts/yield_with_render_partial_inside") end def test_render_with_nested_layout assert_equal %(<title>title</title>\n\n<div id="column">column</div>\n<div id="content">content</div>\n), - buffered_render(:template => "test/nested_layout", :layout => "layouts/yield") + buffered_render(template: "test/nested_layout", layout: "layouts/yield") end def test_render_with_file_in_layout assert_equal %(\n<title>title</title>\n\n), - buffered_render(:template => "test/layout_render_file") + buffered_render(template: "test/layout_render_file") end def test_render_with_handler_without_streaming_support - assert_match "<p>This is grand!</p>", buffered_render(:template => "test/hello") + assert_match "<p>This is grand!</p>", buffered_render(template: "test/hello") end def test_render_with_streaming_multiple_yields_provide_and_content_for assert_equal "Yes, \nthis works\n like a charm.", - buffered_render(:template => "test/streaming", :layout => "layouts/streaming") + buffered_render(template: "test/streaming", layout: "layouts/streaming") end def test_render_with_streaming_with_fake_yields_and_streaming_buster assert_equal "This won't look\n good.", - buffered_render(:template => "test/streaming_buster", :layout => "layouts/streaming") + buffered_render(template: "test/streaming_buster", layout: "layouts/streaming") end def test_render_with_nested_streaming_multiple_yields_provide_and_content_for assert_equal "?Yes, \n\nthis works\n\n? like a charm.", - buffered_render(:template => "test/nested_streaming", :layout => "layouts/streaming") + buffered_render(template: "test/nested_streaming", layout: "layouts/streaming") end def test_render_with_streaming_and_capture @@ -109,3 +113,20 @@ class FiberedTest < ActiveSupport::TestCase buffered_render(template: "test/streaming", layout: "layouts/streaming_with_capture") end end + +class FiberedWithLocaleTest < SetupFiberedBase + def setup + @old_locale = I18n.locale + I18n.locale = "da" + super + end + + def teardown + I18n.locale = @old_locale + end + + def test_render_with_streaming_and_locale + assert_equal "layout.locale: da\nview.locale: da\n\n", + buffered_render(template: "test/streaming_with_locale", layout: "layouts/streaming_with_locale") + end +end diff --git a/actionview/test/template/tag_helper_test.rb b/actionview/test/template/tag_helper_test.rb index f3956a31f6..a746b9c1b5 100644 --- a/actionview/test/template/tag_helper_test.rb +++ b/actionview/test/template/tag_helper_test.rb @@ -1,4 +1,6 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class TagHelperTest < ActionView::TestCase include RenderERBUtils @@ -7,10 +9,28 @@ class TagHelperTest < ActionView::TestCase def test_tag assert_equal "<br />", tag("br") - assert_equal "<br clear=\"left\" />", tag(:br, :clear => "left") + assert_equal "<br clear=\"left\" />", tag(:br, clear: "left") assert_equal "<br>", tag("br", nil, true) end + def test_tag_builder + assert_equal "<span></span>", tag.span + assert_equal "<span class=\"bookmark\"></span>", tag.span(class: "bookmark") + end + + def test_tag_builder_void_tag + assert_equal "<br>", tag.br + assert_equal "<br class=\"some_class\">", tag.br(class: "some_class") + end + + def test_tag_builder_void_tag_with_forced_content + assert_equal "<br>some content</br>", tag.br("some content") + end + + def test_tag_builder_is_singleton + assert_equal tag, tag + end + def test_tag_options str = tag("p", "class" => "show", :class => "elsewhere") assert_match(/class="show"/, str) @@ -18,31 +38,76 @@ class TagHelperTest < ActionView::TestCase end def test_tag_options_rejects_nil_option - assert_equal "<p />", tag("p", :ignored => nil) + assert_equal "<p />", tag("p", ignored: nil) + end + + def test_tag_builder_options_rejects_nil_option + assert_equal "<p></p>", tag.p(ignored: nil) end def test_tag_options_accepts_false_option - assert_equal "<p value=\"false\" />", tag("p", :value => false) + assert_equal "<p value=\"false\" />", tag("p", value: false) + end + + def test_tag_builder_options_accepts_false_option + assert_equal "<p value=\"false\"></p>", tag.p(value: false) end def test_tag_options_accepts_blank_option - assert_equal "<p included=\"\" />", tag("p", :included => '') + assert_equal "<p included=\"\" />", tag("p", included: "") + end + + def test_tag_builder_options_accepts_blank_option + assert_equal "<p included=\"\"></p>", tag.p(included: "") + end + + def test_tag_options_accepts_symbol_option_when_not_escaping + assert_equal "<p value=\"symbol\" />", tag("p", { value: :symbol }, false, false) + end + + def test_tag_options_accepts_integer_option_when_not_escaping + assert_equal "<p value=\"42\" />", tag("p", { value: 42 }, false, false) end def test_tag_options_converts_boolean_option assert_dom_equal '<p disabled="disabled" itemscope="itemscope" multiple="multiple" readonly="readonly" allowfullscreen="allowfullscreen" seamless="seamless" typemustmatch="typemustmatch" sortable="sortable" default="default" inert="inert" truespeed="truespeed" />', - tag("p", :disabled => true, :itemscope => true, :multiple => true, :readonly => true, :allowfullscreen => true, :seamless => true, :typemustmatch => true, :sortable => true, :default => true, :inert => true, :truespeed => true) + tag("p", disabled: true, itemscope: true, multiple: true, readonly: true, allowfullscreen: true, seamless: true, typemustmatch: true, sortable: true, default: true, inert: true, truespeed: true) + end + + def test_tag_builder_options_converts_boolean_option + assert_dom_equal '<p disabled="disabled" itemscope="itemscope" multiple="multiple" readonly="readonly" allowfullscreen="allowfullscreen" seamless="seamless" typemustmatch="typemustmatch" sortable="sortable" default="default" inert="inert" truespeed="truespeed" />', + tag.p(disabled: true, itemscope: true, multiple: true, readonly: true, allowfullscreen: true, seamless: true, typemustmatch: true, sortable: true, default: true, inert: true, truespeed: true) end def test_content_tag assert_equal "<a href=\"create\">Create</a>", content_tag("a", "Create", "href" => "create") assert content_tag("a", "Create", "href" => "create").html_safe? assert_equal content_tag("a", "Create", "href" => "create"), - content_tag("a", "Create", :href => "create") + content_tag("a", "Create", href: "create") + assert_equal "<p><script>evil_js</script></p>", + content_tag(:p, "<script>evil_js</script>") + assert_equal "<p><script>evil_js</script></p>", + content_tag(:p, "<script>evil_js</script>", nil, false) + end + + def test_tag_builder_with_content + assert_equal "<div id=\"post_1\">Content</div>", tag.div("Content", id: "post_1") + assert tag.div("Content", id: "post_1").html_safe? + assert_equal tag.div("Content", id: "post_1"), + tag.div("Content", "id": "post_1") assert_equal "<p><script>evil_js</script></p>", - content_tag(:p, '<script>evil_js</script>') + tag.p("<script>evil_js</script>") assert_equal "<p><script>evil_js</script></p>", - content_tag(:p, '<script>evil_js</script>', nil, false) + tag.p("<script>evil_js</script>", escape_attributes: false) + end + + def test_tag_builder_nested + assert_equal "<div>content</div>", + tag.div { "content" } + assert_equal "<div id=\"header\"><span>hello</span></div>", + tag.div(id: "header") { |tag| tag.span "hello" } + assert_equal "<div id=\"header\"><div class=\"world\"><span>hello</span></div></div>", + tag.div(id: "header") { |tag| tag.div(class: "world") { tag.span "hello" } } end def test_content_tag_with_block_in_erb @@ -50,72 +115,138 @@ class TagHelperTest < ActionView::TestCase assert_dom_equal "<div>Hello world!</div>", buffer end + def test_tag_builder_with_block_in_erb + buffer = render_erb("<%= tag.div do %>Hello world!<% end %>") + 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_tag_builder_with_block_in_erb_containing_non_displayed_erb + buffer = render_erb("<%= 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 end + def test_tag_builder_with_block_and_options_in_erb + buffer = render_erb("<%= tag.div(class: 'green') do %>Hello world!<% end %>") + assert_dom_equal %(<div class="green">Hello world!</div>), buffer + end + def test_content_tag_with_block_and_options_out_of_erb - assert_dom_equal %(<div class="green">Hello world!</div>), content_tag(:div, :class => "green") { "Hello world!" } + assert_dom_equal %(<div class="green">Hello world!</div>), content_tag(:div, class: "green") { "Hello world!" } + end + + def test_tag_builder_with_block_and_options_out_of_erb + assert_dom_equal %(<div class="green">Hello world!</div>), tag.div(class: "green") { "Hello world!" } end def test_content_tag_with_block_and_options_outside_out_of_erb - assert_equal content_tag("a", "Create", :href => "create"), + assert_equal content_tag("a", "Create", href: "create"), content_tag("a", "href" => "create") { "Create" } end + def test_tag_builder_with_block_and_options_outside_out_of_erb + assert_equal tag.a("Create", href: "create"), + 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_tag_builder_with_block_and_non_string_outside_out_of_erb + assert_equal tag.p, + 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") }, output_buffer + assert_equal tag.p(tag.b("Hello")), + tag.p { tag.b("Hello") }, + output_buffer end def test_content_tag_nested_in_content_tag_in_erb assert_equal "<p>\n <b>Hello</b>\n</p>", view.render("test/content_tag_nested_in_content_tag") + assert_equal "<p>\n <b>Hello</b>\n</p>", view.render("test/builder_tag_nested_in_content_tag") end def test_content_tag_with_escaped_array_class - str = content_tag('p', "limelight", :class => ["song", "play>"]) + str = content_tag("p", "limelight", class: ["song", "play>"]) + assert_equal "<p class=\"song play>\">limelight</p>", str + + str = content_tag("p", "limelight", class: ["song", "play"]) + assert_equal "<p class=\"song play\">limelight</p>", str + + str = content_tag("p", "limelight", class: ["song", ["play"]]) + assert_equal "<p class=\"song play\">limelight</p>", str + end + + def test_tag_builder_with_escaped_array_class + str = tag.p "limelight", class: ["song", "play>"] assert_equal "<p class=\"song play>\">limelight</p>", str - str = content_tag('p', "limelight", :class => ["song", "play"]) + str = tag.p "limelight", class: ["song", "play"] assert_equal "<p class=\"song play\">limelight</p>", str - str = content_tag('p', "limelight", :class => ["song", ["play"]]) + str = tag.p "limelight", class: ["song", ["play"]] assert_equal "<p class=\"song play\">limelight</p>", str end def test_content_tag_with_unescaped_array_class - str = content_tag('p', "limelight", {:class => ["song", "play>"]}, false) + str = content_tag("p", "limelight", { class: ["song", "play>"] }, false) assert_equal "<p class=\"song play>\">limelight</p>", str - str = content_tag('p', "limelight", {:class => ["song", ["play>"]]}, false) + str = content_tag("p", "limelight", { class: ["song", ["play>"]] }, false) + assert_equal "<p class=\"song play>\">limelight</p>", str + end + + def test_tag_builder_with_unescaped_array_class + str = tag.p "limelight", class: ["song", "play>"], escape_attributes: false + assert_equal "<p class=\"song play>\">limelight</p>", str + + str = tag.p "limelight", class: ["song", ["play>"]], escape_attributes: false assert_equal "<p class=\"song play>\">limelight</p>", str end def test_content_tag_with_empty_array_class - str = content_tag('p', 'limelight', {:class => []}) + str = content_tag("p", "limelight", class: []) assert_equal '<p class="">limelight</p>', str end + def test_tag_builder_with_empty_array_class + assert_equal '<p class="">limelight</p>', tag.p("limelight", class: []) + end + def test_content_tag_with_unescaped_empty_array_class - str = content_tag('p', 'limelight', {:class => []}, false) + str = content_tag("p", "limelight", { class: [] }, false) + assert_equal '<p class="">limelight</p>', str + end + + def test_tag_builder_with_unescaped_empty_array_class + str = tag.p "limelight", class: [], escape_attributes: false assert_equal '<p class="">limelight</p>', str end def test_content_tag_with_data_attributes assert_dom_equal '<p data-number="1" data-string="hello" data-string-with-quotes="double"quote"party"">limelight</p>', - content_tag('p', "limelight", data: { number: 1, string: 'hello', string_with_quotes: 'double"quote"party"' }) + content_tag("p", "limelight", data: { number: 1, string: "hello", string_with_quotes: 'double"quote"party"' }) + end + + def test_tag_builder_with_data_attributes + assert_dom_equal '<p data-number="1" data-string="hello" data-string-with-quotes="double"quote"party"">limelight</p>', + tag.p("limelight", data: { number: 1, string: "hello", string_with_quotes: 'double"quote"party"' }) end def test_cdata_section @@ -132,51 +263,95 @@ class TagHelperTest < ActionView::TestCase end def test_escape_once - assert_equal '1 < 2 & 3', escape_once('1 < 2 & 3') + assert_equal "1 < 2 & 3", escape_once("1 < 2 & 3") assert_equal " ' ' λ λ " ' < > ", escape_once(" ' ' λ λ \" ' < > ") end def test_tag_honors_html_safe_for_param_values - ['1&2', '1 < 2', '“test“'].each do |escaped| - assert_equal %(<a href="#{escaped}" />), tag('a', :href => escaped.html_safe) + ["1&2", "1 < 2", "“test“"].each do |escaped| + assert_equal %(<a href="#{escaped}" />), tag("a", href: escaped.html_safe) + assert_equal %(<a href="#{escaped}"></a>), tag.a(href: escaped.html_safe) end end def test_tag_honors_html_safe_with_escaped_array_class - str = tag('p', :class => ['song>', raw('play>')]) - assert_equal '<p class="song> play>" />', str + assert_equal '<p class="song> play>" />', tag("p", class: ["song>", raw("play>")]) + assert_equal '<p class="song> play>" />', tag("p", class: [raw("song>"), "play>"]) + end + + def test_tag_builder_honors_html_safe_with_escaped_array_class + assert_equal '<p class="song> play>"></p>', tag.p(class: ["song>", raw("play>")]) + assert_equal '<p class="song> play>"></p>', tag.p(class: [raw("song>"), "play>"]) + end + + def test_tag_does_not_honor_html_safe_double_quotes_as_attributes + assert_dom_equal '<p title=""">content</p>', + content_tag("p", "content", title: '"'.html_safe) + end - str = tag('p', :class => [raw('song>'), 'play>']) - assert_equal '<p class="song> play>" />', str + def test_data_tag_does_not_honor_html_safe_double_quotes_as_attributes + assert_dom_equal '<p data-title=""">content</p>', + content_tag("p", "content", data: { title: '"'.html_safe }) end def test_skip_invalid_escaped_attributes - ['&1;', 'dfa3;', '& #123;'].each do |escaped| - assert_equal %(<a href="#{escaped.gsub(/&/, '&')}" />), tag('a', :href => escaped) + ["&1;", "dfa3;", "& #123;"].each do |escaped| + assert_equal %(<a href="#{escaped.gsub(/&/, '&')}" />), tag("a", href: escaped) + assert_equal %(<a href="#{escaped.gsub(/&/, '&')}"></a>), tag.a(href: escaped) end end def test_disable_escaping - assert_equal '<a href="&" />', tag('a', { :href => '&' }, false, false) + assert_equal '<a href="&" />', tag("a", { href: "&" }, false, false) + end + + def test_tag_builder_disable_escaping + assert_equal '<a href="&"></a>', tag.a(href: "&", escape_attributes: false) + assert_equal '<a href="&">cnt</a>', tag.a(href: "&", escape_attributes: false) { "cnt" } + assert_equal '<br data-hidden="&">', tag.br("data-hidden": "&", escape_attributes: false) + assert_equal '<a href="&">content</a>', tag.a("content", href: "&", escape_attributes: false) + assert_equal '<a href="&">content</a>', tag.a(href: "&", escape_attributes: false) { "content" } end def test_data_attributes - ['data', :data].each { |data| + ["data", :data].each { |data| assert_dom_equal '<a data-a-float="3.14" data-a-big-decimal="-123.456" data-a-number="1" data-array="[1,2,3]" data-hash="{"key":"value"}" data-string-with-quotes="double"quote"party"" data-string="hello" data-symbol="foo" />', - tag('a', { data => { a_float: 3.14, a_big_decimal: BigDecimal.new("-123.456"), a_number: 1, string: 'hello', symbol: :foo, array: [1, 2, 3], hash: { key: 'value'}, string_with_quotes: 'double"quote"party"' } }) + tag("a", data => { a_float: 3.14, a_big_decimal: BigDecimal("-123.456"), a_number: 1, string: "hello", symbol: :foo, array: [1, 2, 3], hash: { key: "value" }, string_with_quotes: 'double"quote"party"' }) + assert_dom_equal '<a data-a-float="3.14" data-a-big-decimal="-123.456" data-a-number="1" data-array="[1,2,3]" data-hash="{"key":"value"}" data-string-with-quotes="double"quote"party"" data-string="hello" data-symbol="foo" />', + tag.a(data: { a_float: 3.14, a_big_decimal: BigDecimal("-123.456"), a_number: 1, string: "hello", symbol: :foo, array: [1, 2, 3], hash: { key: "value" }, string_with_quotes: 'double"quote"party"' }) } end def test_aria_attributes - ['aria', :aria].each { |aria| + ["aria", :aria].each { |aria| + assert_dom_equal '<a aria-a-float="3.14" aria-a-big-decimal="-123.456" aria-a-number="1" aria-array="[1,2,3]" aria-hash="{"key":"value"}" aria-string-with-quotes="double"quote"party"" aria-string="hello" aria-symbol="foo" />', + tag("a", aria => { a_float: 3.14, a_big_decimal: BigDecimal("-123.456"), a_number: 1, string: "hello", symbol: :foo, array: [1, 2, 3], hash: { key: "value" }, string_with_quotes: 'double"quote"party"' }) assert_dom_equal '<a aria-a-float="3.14" aria-a-big-decimal="-123.456" aria-a-number="1" aria-array="[1,2,3]" aria-hash="{"key":"value"}" aria-string-with-quotes="double"quote"party"" aria-string="hello" aria-symbol="foo" />', - tag('a', { aria => { a_float: 3.14, a_big_decimal: BigDecimal.new("-123.456"), a_number: 1, string: 'hello', symbol: :foo, array: [1, 2, 3], hash: { key: 'value'}, string_with_quotes: 'double"quote"party"' } }) + tag.a(aria: { a_float: 3.14, a_big_decimal: BigDecimal("-123.456"), a_number: 1, string: "hello", symbol: :foo, array: [1, 2, 3], hash: { key: "value" }, string_with_quotes: 'double"quote"party"' }) } end def test_link_to_data_nil_equal - div_type1 = content_tag(:div, 'test', { 'data-tooltip' => nil }) - div_type2 = content_tag(:div, 'test', { data: {tooltip: nil} }) - assert_dom_equal div_type1, div_type2 + div_type1 = content_tag(:div, "test", "data-tooltip" => nil) + div_type2 = content_tag(:div, "test", data: { tooltip: nil }) + assert_dom_equal div_type1, div_type2 + end + + def test_tag_builder_link_to_data_nil_equal + div_type1 = tag.div "test", 'data-tooltip': nil + div_type2 = tag.div "test", data: { tooltip: nil } + assert_dom_equal div_type1, div_type2 + end + + def test_tag_builder_allow_call_via_method_object + assert_equal "<foo></foo>", tag.method(:foo).call + end + + def test_tag_builder_dasherize_names + assert_equal "<img-slider></img-slider>", tag.img_slider + end + + def test_respond_to + assert_respond_to tag, :any_tag end end diff --git a/actionview/test/template/template_error_test.rb b/actionview/test/template/template_error_test.rb index 54c1d53b60..c4dc88e4aa 100644 --- a/actionview/test/template/template_error_test.rb +++ b/actionview/test/template/template_error_test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require "abstract_unit" class TemplateErrorTest < ActiveSupport::TestCase diff --git a/actionview/test/template/template_test.rb b/actionview/test/template/template_test.rb index 533c1c3219..3dc14e36e0 100644 --- a/actionview/test/template/template_test.rb +++ b/actionview/test/template/template_test.rb @@ -1,4 +1,6 @@ # encoding: US-ASCII +# frozen_string_literal: true + require "abstract_unit" require "logger" @@ -35,7 +37,7 @@ class TestERBTemplate < ActiveSupport::TestCase "<%= @virtual_path %>", "partial", ERBHandler, - :virtual_path => "partial" + virtual_path: "partial" ) end @@ -53,7 +55,7 @@ class TestERBTemplate < ActiveSupport::TestCase end def new_template(body = "<%= hello %>", details = { format: :html }) - ActionView::Template.new(body, "hello template", details.fetch(:handler) { ERBHandler }, {:virtual_path => "hello"}.merge!(details)) + ActionView::Template.new(body.dup, "hello template", details.fetch(:handler) { ERBHandler }, { virtual_path: "hello" }.merge!(details)) end def render(locals = {}) @@ -80,7 +82,7 @@ class TestERBTemplate < ActiveSupport::TestCase end def test_raw_template - @template = new_template("<%= hello %>", :handler => ActionView::Template::Handlers::Raw.new) + @template = new_template("<%= hello %>", handler: ActionView::Template::Handlers::Raw.new) assert_equal "<%= hello %>", render end @@ -91,7 +93,7 @@ class TestERBTemplate < ActiveSupport::TestCase end def test_template_does_not_lose_its_source_after_rendering_if_it_does_not_have_a_virtual_path - @template = new_template("Hello", :virtual_path => nil) + @template = new_template("Hello", virtual_path: nil) render assert_equal "Hello", @template.source end @@ -99,7 +101,7 @@ class TestERBTemplate < ActiveSupport::TestCase def test_locals @template = new_template("<%= my_local %>") @template.locals = [:my_local] - assert_equal "I am a local", render(:my_local => "I am a local") + assert_equal "I am a local", render(my_local: "I am a local") end def test_restores_buffer @@ -116,23 +118,23 @@ class TestERBTemplate < ActiveSupport::TestCase end def test_refresh_with_templates - @template = new_template("Hello", :virtual_path => "test/foo/bar") + @template = new_template("Hello", virtual_path: "test/foo/bar") @template.locals = [:key] - assert_called_with(@context.lookup_context, :find_template,["bar", %w(test/foo), false, [:key]], returns: "template") do + 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 = new_template("Hello", virtual_path: "test/_foo") @template.locals = [:key] - assert_called_with(@context.lookup_context, :find_template,[ "foo", %w(test), true, [:key]], returns: "partial") do + 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 - @template = new_template("Hello", :virtual_path => nil) + @template = new_template("Hello", virtual_path: nil) assert_raise RuntimeError do @template.refresh(@context) end @@ -171,14 +173,14 @@ class TestERBTemplate < ActiveSupport::TestCase # inside Rails. def test_lying_with_magic_comment assert_raises(ActionView::Template::Error) do - @template = new_template("# encoding: UTF-8\nhello \xFCmlat", :virtual_path => nil) + @template = new_template("# encoding: UTF-8\nhello \xFCmlat", virtual_path: nil) render end end def test_encoding_can_be_specified_with_magic_comment_in_erb with_external_encoding Encoding::UTF_8 do - @template = new_template("<%# encoding: ISO-8859-1 %>hello \xFCmlat", :virtual_path => nil) + @template = new_template("<%# encoding: ISO-8859-1 %>hello \xFCmlat", virtual_path: nil) assert_equal Encoding::UTF_8, render.encoding assert_equal "hello \u{fc}mlat", render end @@ -186,10 +188,12 @@ class TestERBTemplate < ActiveSupport::TestCase def test_error_when_template_isnt_valid_utf8 e = assert_raises ActionView::Template::Error do - @template = new_template("hello \xFCmlat", :virtual_path => nil) + @template = new_template("hello \xFCmlat", virtual_path: nil) render end - assert_match(/\xFC/, e.message) + # Hack: We write the regexp this way because the parser of RuboCop + # errs with /\xFC/. + assert_match(Regexp.new("\xFC"), e.message) 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 d69d5819b6..05e5f21ce4 100644 --- a/actionview/test/template/test_case_test.rb +++ b/actionview/test/template/test_case_test.rb @@ -1,20 +1,21 @@ -require 'abstract_unit' -require 'rails/engine' +# frozen_string_literal: true -module ActionView +require "abstract_unit" +require "rails/engine" +module ActionView module ATestHelper end module AnotherTestHelper def from_another_helper - 'Howdy!' + "Howdy!" end end module ASharedTestHelper def from_shared_helper - 'Holla!' + "Holla!" end end @@ -26,8 +27,8 @@ module ActionView def self.included(test_case) test_case.class_eval do test "helpers defined on ActionView::TestCase are available" do - assert test_case.ancestors.include?(ASharedTestHelper) - assert_equal 'Holla!', from_shared_helper + assert_includes test_case.ancestors, ASharedTestHelper + assert_equal "Holla!", from_shared_helper end end end @@ -51,22 +52,22 @@ module ActionView end test "retrieve non existing config values" do - assert_equal nil, ActionView::Base.new.config.something_odd + assert_nil ActionView::Base.new.config.something_odd end test "works without testing a helper module" do - assert_equal 'Eloy', render('developers/developer', :developer => DeveloperStruct.new('Eloy')) + assert_equal "Eloy", render("developers/developer", developer: DeveloperStruct.new("Eloy")) end test "can render a layout with block" do assert_equal "Before (ChrisCruft)\n!\nAfter", - render(:layout => "test/layout_for_partial", :locals => {:name => "ChrisCruft"}) {"!"} + render(layout: "test/layout_for_partial", locals: { name: "ChrisCruft" }) { "!" } end helper AnotherTestHelper test "additional helper classes can be specified as in a controller" do - assert test_case.ancestors.include?(AnotherTestHelper) - assert_equal 'Howdy!', from_another_helper + assert_includes test_case.ancestors, AnotherTestHelper + assert_equal "Howdy!", from_another_helper end test "determine_default_helper_class returns nil if the test name constant resolves to a class" do @@ -86,7 +87,7 @@ module ActionView end test "uses controller lookup context" do - assert_equal self.lookup_context, @controller.lookup_context + assert_equal lookup_context, @controller.lookup_context end end @@ -97,44 +98,44 @@ module ActionView tests ATestHelper test "tests the specified helper module" do assert_equal ATestHelper, test_case.helper_class - assert test_case.ancestors.include?(ATestHelper) + assert_includes test_case.ancestors, ATestHelper end helper AnotherTestHelper test "additional helper classes can be specified as in a controller" do - assert test_case.ancestors.include?(AnotherTestHelper) - assert_equal 'Howdy!', from_another_helper + assert_includes test_case.ancestors, AnotherTestHelper + assert_equal "Howdy!", from_another_helper test_case.helper_class.module_eval do def render_from_helper from_another_helper end end - assert_equal 'Howdy!', render(:partial => 'test/from_helper') + assert_equal "Howdy!", render(partial: "test/from_helper") end end class HelperInclusionTest < ActionView::TestCase module RenderHelper def render_from_helper - render :partial => 'customer', :collection => @customers + render partial: "customer", collection: @customers end end helper RenderHelper test "helper class that is being tested is always included in view instance" do - @controller.controller_path = 'test' + @controller.controller_path = "test" - @customers = [DeveloperStruct.new('Eloy'), DeveloperStruct.new('Manfred')] - assert_match(/Hello: EloyHello: Manfred/, render(:partial => 'test/from_helper')) + @customers = [DeveloperStruct.new("Eloy"), DeveloperStruct.new("Manfred")] + assert_match(/Hello: EloyHello: Manfred/, render(partial: "test/from_helper")) end end class ControllerHelperMethod < ActionView::TestCase module SomeHelper def some_method - render :partial => 'test/from_helper' + render partial: "test/from_helper" end end @@ -148,21 +149,21 @@ module ActionView EOF @controller.class.helper_method :render_from_helper - assert_equal 'controller_helper_method', some_method + assert_equal "controller_helper_method", some_method end end class ViewAssignsTest < ActionView::TestCase test "view_assigns returns a Hash of user defined ivars" do - @a = 'b' - @c = 'd' - assert_equal({:a => 'b', :c => 'd'}, view_assigns) + @a = "b" + @c = "d" + assert_equal({ a: "b", c: "d" }, view_assigns) end test "view_assigns excludes internal ivars" do INTERNAL_IVARS.each do |ivar| assert defined?(ivar), "expected #{ivar} to be defined" - assert !view_assigns.keys.include?(ivar.to_s.tr('@', '').to_sym), "expected #{ivar} to be excluded from view_assigns" + assert_not_includes view_assigns.keys, ivar.to_s.tr("@", "").to_sym, "expected #{ivar} to be excluded from view_assigns" end end end @@ -174,10 +175,10 @@ module ActionView end end) test "is able to make methods available to the view" do - assert_equal 'Word!', render(:partial => 'test/from_helper') + assert_equal "Word!", render(partial: "test/from_helper") end - def from_test_case; 'Word!'; end + def from_test_case; "Word!"; end helper_method :from_test_case end @@ -193,7 +194,6 @@ module ActionView test "protect_from_forgery? in any helpers returns false" do assert !view.help_me end - end class ATestHelperTest < ActionView::TestCase @@ -202,30 +202,30 @@ module ActionView test "inflects the name of the helper module to test from the test case class" do assert_equal ATestHelper, test_case.helper_class - assert test_case.ancestors.include?(ATestHelper) + assert_includes test_case.ancestors, ATestHelper end test "a configured test controller is available" do assert_kind_of ActionController::Base, controller - assert_equal '', controller.controller_path + assert_equal "", controller.controller_path end test "no additional helpers should shared across test cases" do - assert !test_case.ancestors.include?(AnotherTestHelper) + assert_not_includes test_case.ancestors, AnotherTestHelper assert_raise(NoMethodError) { send :from_another_helper } end test "is able to use routes" do - controller.request.assign_parameters(@routes, 'foo', 'index', {}, '/foo', []) - assert_equal '/foo', url_for - assert_equal '/bar', url_for(:controller => 'bar') + controller.request.assign_parameters(@routes, "foo", "index", {}, "/foo", []) + assert_equal "/foo", url_for + assert_equal "/bar", url_for(controller: "bar") end test "is able to use named routes" do with_routing do |set| set.draw { resources :contents } - assert_equal 'http://test.host/contents/new', new_content_url - assert_equal 'http://test.host/contents/1', content_url(:id => 1) + assert_equal "http://test.host/contents/new", new_content_url + assert_equal "http://test.host/contents/1", content_url(id: 1) end end @@ -236,7 +236,7 @@ module ActionView @routes ||= ActionDispatch::Routing::RouteSet.new end - routes.draw { get "bar", :to => lambda {} } + routes.draw { get "bar", to: lambda {} } def self.call(*) end @@ -244,7 +244,7 @@ module ActionView set.draw { mount app => "/foo", :as => "foo_app" } - assert_equal '/foo/bar', foo_app.bar_path + assert_equal "/foo/bar", foo_app.bar_path end end @@ -257,21 +257,21 @@ module ActionView end end - assert_equal 'http://test.host/contents/new', render(:partial => 'test/from_helper') + assert_equal "http://test.host/contents/new", render(partial: "test/from_helper") end end test "is able to render partials with local variables" do - assert_equal 'Eloy', render('developers/developer', :developer => DeveloperStruct.new('Eloy')) - assert_equal 'Eloy', render(:partial => 'developers/developer', - :locals => { :developer => DeveloperStruct.new('Eloy') }) + assert_equal "Eloy", render("developers/developer", developer: DeveloperStruct.new("Eloy")) + assert_equal "Eloy", render(partial: "developers/developer", + 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 = [DeveloperStruct.new('Eloy'), DeveloperStruct.new('Manfred')] - assert_match(/Hello: EloyHello: Manfred/, render(:file => 'test/list')) + @customers = [DeveloperStruct.new("Eloy"), DeveloperStruct.new("Manfred")] + assert_match(/Hello: EloyHello: Manfred/, render(file: "test/list")) end test "is able to render partials from templates and also use instance variables after view has been referenced" do @@ -279,37 +279,44 @@ module ActionView view - @customers = [DeveloperStruct.new('Eloy'), DeveloperStruct.new('Manfred')] - assert_match(/Hello: EloyHello: Manfred/, render(:file => 'test/list')) + @customers = [DeveloperStruct.new("Eloy"), DeveloperStruct.new("Manfred")] + assert_match(/Hello: EloyHello: Manfred/, render(file: "test/list")) end + test "is able to use helpers that depend on the view flow" do + assert_not content_for?(:foo) + + content_for :foo, "bar" + assert content_for?(:foo) + assert_equal "bar", content_for(:foo) + end end class AssertionsTest < ActionView::TestCase def render_from_helper - form_tag('/foo') do - safe_concat render(:text => '<ul><li>foo</li></ul>') + form_tag("/foo") do + safe_concat render(plain: "<ul><li>foo</li></ul>") end end helper_method :render_from_helper test "uses the output_buffer for assert_select" do - render(:partial => 'test/from_helper') + render(partial: "test/from_helper") - assert_select 'form' do - assert_select 'li', :text => 'foo' + assert_select "form" do + assert_select "li", text: "foo" end end test "do not memoize the document_root_element in view tests" do - concat form_tag('/foo') + concat form_tag("/foo") - assert_select 'form' + assert_select "form" - concat content_tag(:b, 'Strong', class: 'foo') + concat content_tag(:b, "Strong", class: "foo") - assert_select 'form' - assert_select 'b.foo' + assert_select "form" + assert_select "b.foo" end end diff --git a/actionview/test/template/test_test.rb b/actionview/test/template/test_test.rb index e1ff639979..78ba536dfc 100644 --- a/actionview/test/template/test_test.rb +++ b/actionview/test/template/test_test.rb @@ -1,4 +1,6 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" module PeopleHelper def title(text) @@ -41,7 +43,7 @@ class PeopleHelperTest < ActionView::TestCase extend ActiveModel::Naming def to_model; self; end def persisted?; true; end - def self.name; 'Minitest::Mock'; end + def self.name; "Minitest::Mock"; end }.new "David" the_model = nil @@ -60,7 +62,7 @@ class PeopleHelperTest < ActionView::TestCase def with_test_route_set with_routing do |set| set.draw do - get 'people', :to => 'people#index', :as => :people + get "people", to: "people#index", as: :people end yield end @@ -84,7 +86,7 @@ class CrazySymbolHelperTest < ActionView::TestCase end class CrazyStringHelperTest < ActionView::TestCase - tests 'people' + tests "people" def test_set_helper_class_using_string assert_equal PeopleHelper, self.class.helper_class diff --git a/actionview/test/template/testing/fixture_resolver_test.rb b/actionview/test/template/testing/fixture_resolver_test.rb index d6cfa997cd..9954e3500d 100644 --- a/actionview/test/template/testing/fixture_resolver_test.rb +++ b/actionview/test/template/testing/fixture_resolver_test.rb @@ -1,15 +1,17 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class FixtureResolverTest < ActiveSupport::TestCase def test_should_return_empty_list_for_unknown_path resolver = ActionView::FixtureResolver.new() - templates = resolver.find_all("path", "arbitrary", false, {:locale => [], :formats => [:html], :variants => [], :handlers => []}) + templates = resolver.find_all("path", "arbitrary", false, locale: [], formats: [:html], variants: [], handlers: []) assert_equal [], templates, "expected an empty list of templates" end def test_should_return_template_for_declared_path resolver = ActionView::FixtureResolver.new("arbitrary/path.erb" => "this text") - templates = resolver.find_all("path", "arbitrary", false, {:locale => [], :formats => [:html], :variants => [], :handlers => [:erb]}) + templates = resolver.find_all("path", "arbitrary", false, locale: [], formats: [:html], variants: [], handlers: [:erb]) assert_equal 1, templates.size, "expected one template" assert_equal "this text", templates.first.source assert_equal "arbitrary/path", templates.first.virtual_path diff --git a/actionview/test/template/testing/null_resolver_test.rb b/actionview/test/template/testing/null_resolver_test.rb index 55ec36e753..53364c1d90 100644 --- a/actionview/test/template/testing/null_resolver_test.rb +++ b/actionview/test/template/testing/null_resolver_test.rb @@ -1,9 +1,11 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class NullResolverTest < ActiveSupport::TestCase def test_should_return_template_for_any_path resolver = ActionView::NullResolver.new() - templates = resolver.find_all("path.erb", "arbitrary", false, {:locale => [], :formats => [:html], :handlers => []}) + templates = resolver.find_all("path.erb", "arbitrary", false, locale: [], formats: [:html], handlers: []) assert_equal 1, templates.size, "expected one template" assert_equal "Template generated by Null Resolver", templates.first.source assert_equal "arbitrary/path.erb", templates.first.virtual_path.to_s diff --git a/actionview/test/template/text_helper_test.rb b/actionview/test/template/text_helper_test.rb index 03c7597505..f247de066f 100644 --- a/actionview/test/template/text_helper_test.rb +++ b/actionview/test/template/text_helper_test.rb @@ -1,4 +1,6 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class TextHelperTest < ActionView::TestCase tests ActionView::Helpers::TextHelper @@ -11,9 +13,9 @@ class TextHelperTest < ActionView::TestCase end def test_concat - self.output_buffer = 'foo' - assert_equal 'foobar', concat('bar') - assert_equal 'foobar', output_buffer + self.output_buffer = "foo".dup + assert_equal "foobar", concat("bar") + assert_equal "foobar", output_buffer end def test_simple_format_should_be_html_safe @@ -38,8 +40,8 @@ class TextHelperTest < ActionView::TestCase text = "A\r\n \nB\n\n\r\n\t\nC\nD".freeze assert_equal "<p>A\n<br /> \n<br />B</p>\n\n<p>\t\n<br />C\n<br />D</p>", simple_format(text) - assert_equal %q(<p class="test">This is a classy test</p>), simple_format("This is a classy test", :class => 'test') - assert_equal %Q(<p class="test">para 1</p>\n\n<p class="test">para 2</p>), simple_format("para 1\n\npara 2", :class => 'test') + assert_equal '<p class="test">This is a classy test</p>', simple_format("This is a classy test", class: "test") + assert_equal %Q(<p class="test">para 1</p>\n\n<p class="test">para 2</p>), simple_format("para 1\n\npara 2", class: "test") end def test_simple_format_should_sanitize_input_when_sanitize_option_is_not_false @@ -47,20 +49,20 @@ class TextHelperTest < ActionView::TestCase end def test_simple_format_should_sanitize_input_when_sanitize_option_is_true - assert_equal '<p><b> test with unsafe string </b>code!</p>', - simple_format('<b> test with unsafe string </b><script>code!</script>', {}, sanitize: true) + assert_equal "<p><b> test with unsafe string </b>code!</p>", + simple_format("<b> test with unsafe string </b><script>code!</script>", {}, { sanitize: true }) end def test_simple_format_should_not_sanitize_input_when_sanitize_option_is_false - assert_equal "<p><b> test with unsafe string </b><script>code!</script></p>", simple_format("<b> test with unsafe string </b><script>code!</script>", {}, :sanitize => false) + assert_equal "<p><b> test with unsafe string </b><script>code!</script></p>", simple_format("<b> test with unsafe string </b><script>code!</script>", {}, { sanitize: false }) end def test_simple_format_with_custom_wrapper - assert_equal "<div></div>", simple_format(nil, {}, :wrapper_tag => "div") + assert_equal "<div></div>", simple_format(nil, {}, { wrapper_tag: "div" }) end def test_simple_format_with_custom_wrapper_and_multi_line_breaks - assert_equal "<div>We want to put a wrapper...</div>\n\n<div>...right there.</div>", simple_format("We want to put a wrapper...\n\n...right there.", {}, :wrapper_tag => "div") + assert_equal "<div>We want to put a wrapper...</div>\n\n<div>...right there.</div>", simple_format("We want to put a wrapper...\n\n...right there.", {}, { wrapper_tag: "div" }) end def test_simple_format_should_not_change_the_text_passed @@ -71,22 +73,22 @@ class TextHelperTest < ActionView::TestCase end def test_simple_format_does_not_modify_the_html_options_hash - options = { :class => "foobar"} + options = { class: "foobar" } passed_options = options.dup simple_format("some text", passed_options) assert_equal options, passed_options end def test_simple_format_does_not_modify_the_options_hash - options = { :wrapper_tag => :div, :sanitize => false } + options = { wrapper_tag: :div, sanitize: false } passed_options = options.dup simple_format("some text", {}, passed_options) assert_equal options, passed_options end def test_truncate - assert_equal "Hello World!", truncate("Hello World!", :length => 12) - assert_equal "Hello Wor...", truncate("Hello World!!", :length => 12) + assert_equal "Hello World!", truncate("Hello World!", length: 12) + assert_equal "Hello Wor...", truncate("Hello World!!", length: 12) end def test_truncate_should_use_default_length_of_30 @@ -95,21 +97,21 @@ class TextHelperTest < ActionView::TestCase end def test_truncate_with_options_hash - assert_equal "This is a string that wil[...]", truncate("This is a string that will go longer then the default truncate length of 30", :omission => "[...]") - assert_equal "Hello W...", truncate("Hello World!", :length => 10) - assert_equal "Hello[...]", truncate("Hello World!", :omission => "[...]", :length => 10) - assert_equal "Hello[...]", truncate("Hello Big World!", :omission => "[...]", :length => 13, :separator => ' ') - assert_equal "Hello Big[...]", truncate("Hello Big World!", :omission => "[...]", :length => 14, :separator => ' ') - assert_equal "Hello Big[...]", truncate("Hello Big World!", :omission => "[...]", :length => 15, :separator => ' ') + assert_equal "This is a string that wil[...]", truncate("This is a string that will go longer then the default truncate length of 30", omission: "[...]") + assert_equal "Hello W...", truncate("Hello World!", length: 10) + assert_equal "Hello[...]", truncate("Hello World!", omission: "[...]", length: 10) + assert_equal "Hello[...]", truncate("Hello Big World!", omission: "[...]", length: 13, separator: " ") + assert_equal "Hello Big[...]", truncate("Hello Big World!", omission: "[...]", length: 14, separator: " ") + assert_equal "Hello Big[...]", truncate("Hello Big World!", omission: "[...]", length: 15, separator: " ") end def test_truncate_multibyte - assert_equal "\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 ...".force_encoding(Encoding::UTF_8), - truncate("\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 \354\225\204\353\235\274\353\246\254\354\230\244".force_encoding(Encoding::UTF_8), :length => 10) + assert_equal "\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 ...".dup.force_encoding(Encoding::UTF_8), + truncate("\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 \354\225\204\353\235\274\353\246\254\354\230\244".dup.force_encoding(Encoding::UTF_8), length: 10) end def test_truncate_does_not_modify_the_options_hash - options = { :length => 10 } + options = { length: 10 } passed_options = options.dup truncate("some text", passed_options) assert_equal options, passed_options @@ -117,49 +119,49 @@ class TextHelperTest < ActionView::TestCase def test_truncate_with_link_options assert_equal "Here is a long test and ...<a href=\"#\">Continue</a>", - truncate("Here is a long test and I need a continue to read link", :length => 27) { link_to 'Continue', '#' } + truncate("Here is a long test and I need a continue to read link", length: 27) { link_to "Continue", "#" } end def test_truncate_should_be_html_safe - assert truncate("Hello World!", :length => 12).html_safe? + assert truncate("Hello World!", length: 12).html_safe? end def test_truncate_should_escape_the_input - assert_equal "Hello <sc...", truncate("Hello <script>code!</script>World!!", :length => 12) + assert_equal "Hello <sc...", truncate("Hello <script>code!</script>World!!", length: 12) end def test_truncate_should_not_escape_the_input_with_escape_false - assert_equal "Hello <sc...", truncate("Hello <script>code!</script>World!!", :length => 12, :escape => false) + assert_equal "Hello <sc...", truncate("Hello <script>code!</script>World!!", length: 12, escape: false) end def test_truncate_with_escape_false_should_be_html_safe - truncated = truncate("Hello <script>code!</script>World!!", :length => 12, :escape => false) + truncated = truncate("Hello <script>code!</script>World!!", length: 12, escape: false) assert truncated.html_safe? end def test_truncate_with_block_should_be_html_safe - truncated = truncate("Here's a long test and I need a continue to read link", :length => 27) { link_to 'Continue', '#' } + truncated = truncate("Here's a long test and I need a continue to read link", length: 27) { link_to "Continue", "#" } assert truncated.html_safe? end def test_truncate_with_block_should_escape_the_input assert_equal "<script>code!</script>He...<a href=\"#\">Continue</a>", - truncate("<script>code!</script>Here's a long test and I need a continue to read link", :length => 27) { link_to 'Continue', '#' } + truncate("<script>code!</script>Here's a long test and I need a continue to read link", length: 27) { link_to "Continue", "#" } end def test_truncate_with_block_should_not_escape_the_input_with_escape_false assert_equal "<script>code!</script>He...<a href=\"#\">Continue</a>", - truncate("<script>code!</script>Here's a long test and I need a continue to read link", :length => 27, :escape => false) { link_to 'Continue', '#' } + truncate("<script>code!</script>Here's a long test and I need a continue to read link", length: 27, escape: false) { link_to "Continue", "#" } end def test_truncate_with_block_with_escape_false_should_be_html_safe - truncated = truncate("<script>code!</script>Here's a long test and I need a continue to read link", :length => 27, :escape => false) { link_to 'Continue', '#' } + truncated = truncate("<script>code!</script>Here's a long test and I need a continue to read link", length: 27, escape: false) { link_to "Continue", "#" } assert truncated.html_safe? end def test_truncate_with_block_should_escape_the_block assert_equal "Here is a long test and ...<script>alert('foo');</script>", - truncate("Here is a long test and I need a continue to read link", :length => 27) { "<script>alert('foo');</script>" } + truncate("Here is a long test and I need a continue to read link", length: 27) { "<script>alert('foo');</script>" } end def test_highlight_should_be_html_safe @@ -179,7 +181,7 @@ class TextHelperTest < ActionView::TestCase assert_equal( "This is a <b>beautiful</b> morning, but also a <b>beautiful</b> day", - highlight("This is a beautiful morning, but also a beautiful day", "beautiful", :highlighter => '<b>\1</b>') + highlight("This is a beautiful morning, but also a beautiful day", "beautiful", highlighter: '<b>\1</b>') ) assert_equal( @@ -189,11 +191,11 @@ class TextHelperTest < ActionView::TestCase end def test_highlight_pending - assert_equal ' ', highlight(' ', 'blank text is returned verbatim') + assert_equal " ", highlight(" ", "blank text is returned verbatim") end def test_highlight_should_return_blank_string_for_nil - assert_equal '', highlight(nil, 'blank string is returned for nil') + assert_equal "", highlight(nil, "blank string is returned for nil") end def test_highlight_should_sanitize_input @@ -206,7 +208,7 @@ class TextHelperTest < ActionView::TestCase def test_highlight_should_not_sanitize_if_sanitize_option_if_false assert_equal( "This is a <mark>beautiful</mark> morning<script>code!</script>", - highlight("This is a beautiful morning<script>code!</script>", "beautiful", :sanitize => false) + highlight("This is a beautiful morning<script>code!</script>", "beautiful", sanitize: false) ) end @@ -233,7 +235,7 @@ class TextHelperTest < ActionView::TestCase end def test_highlight_with_multiple_phrases_in_one_pass - assert_equal %(<em>wow</em> <em>em</em>), highlight('wow em', %w(wow em), :highlighter => '<em>\1</em>') + assert_equal %(<em>wow</em> <em>em</em>), highlight("wow em", %w(wow em), highlighter: '<em>\1</em>') end def test_highlight_with_html @@ -259,12 +261,12 @@ class TextHelperTest < ActionView::TestCase ) assert_equal( "<div>abc <b>div</b></div>", - highlight("<div>abc div</div>", "div", :highlighter => '<b>\1</b>') + highlight("<div>abc div</div>", "div", highlighter: '<b>\1</b>') ) end def test_highlight_does_not_modify_the_options_hash - options = { :highlighter => '<b>\1</b>', :sanitize => false } + options = { highlighter: '<b>\1</b>', sanitize: false } passed_options = options.dup highlight("<div>abc div</div>", "div", passed_options) assert_equal options, passed_options @@ -278,89 +280,89 @@ class TextHelperTest < ActionView::TestCase end def test_excerpt - assert_equal("...is a beautiful morn...", excerpt("This is a beautiful morning", "beautiful", :radius => 5)) - assert_equal("This is a...", excerpt("This is a beautiful morning", "this", :radius => 5)) - assert_equal("...iful morning", excerpt("This is a beautiful morning", "morning", :radius => 5)) + assert_equal("...is a beautiful morn...", excerpt("This is a beautiful morning", "beautiful", radius: 5)) + assert_equal("This is a...", excerpt("This is a beautiful morning", "this", radius: 5)) + assert_equal("...iful morning", excerpt("This is a beautiful morning", "morning", radius: 5)) assert_nil excerpt("This is a beautiful morning", "day") end def test_excerpt_with_regex - assert_equal('...is a beautiful! mor...', excerpt('This is a beautiful! morning', 'beautiful', :radius => 5)) - assert_equal('...is a beautiful? mor...', excerpt('This is a beautiful? morning', 'beautiful', :radius => 5)) - assert_equal('...is a beautiful? mor...', excerpt('This is a beautiful? morning', /\bbeau\w*\b/i, :radius => 5)) - assert_equal('...is a beautiful? mor...', excerpt('This is a beautiful? morning', /\b(beau\w*)\b/i, :radius => 5)) - assert_equal("...udge Allen and...", excerpt("This day was challenging for judge Allen and his colleagues.", /\ballen\b/i, :radius => 5)) - assert_equal("...judge Allen and...", excerpt("This day was challenging for judge Allen and his colleagues.", /\ballen\b/i, :radius => 1, :separator => ' ')) - assert_equal("...was challenging for...", excerpt("This day was challenging for judge Allen and his colleagues.", /\b(\w*allen\w*)\b/i, :radius => 5)) + assert_equal("...is a beautiful! mor...", excerpt("This is a beautiful! morning", "beautiful", radius: 5)) + assert_equal("...is a beautiful? mor...", excerpt("This is a beautiful? morning", "beautiful", radius: 5)) + assert_equal("...is a beautiful? mor...", excerpt("This is a beautiful? morning", /\bbeau\w*\b/i, radius: 5)) + assert_equal("...is a beautiful? mor...", excerpt("This is a beautiful? morning", /\b(beau\w*)\b/i, radius: 5)) + assert_equal("...udge Allen and...", excerpt("This day was challenging for judge Allen and his colleagues.", /\ballen\b/i, radius: 5)) + assert_equal("...judge Allen and...", excerpt("This day was challenging for judge Allen and his colleagues.", /\ballen\b/i, radius: 1, separator: " ")) + assert_equal("...was challenging for...", excerpt("This day was challenging for judge Allen and his colleagues.", /\b(\w*allen\w*)\b/i, radius: 5)) end def test_excerpt_should_not_be_html_safe - assert !excerpt('This is a beautiful! morning', 'beautiful', :radius => 5).html_safe? + assert !excerpt("This is a beautiful! morning", "beautiful", radius: 5).html_safe? end def test_excerpt_in_borderline_cases - assert_equal("", excerpt("", "", :radius => 0)) - assert_equal("a", excerpt("a", "a", :radius => 0)) - assert_equal("...b...", excerpt("abc", "b", :radius => 0)) - assert_equal("abc", excerpt("abc", "b", :radius => 1)) - assert_equal("abc...", excerpt("abcd", "b", :radius => 1)) - assert_equal("...abc", excerpt("zabc", "b", :radius => 1)) - assert_equal("...abc...", excerpt("zabcd", "b", :radius => 1)) - assert_equal("zabcd", excerpt("zabcd", "b", :radius => 2)) + assert_equal("", excerpt("", "", radius: 0)) + assert_equal("a", excerpt("a", "a", radius: 0)) + assert_equal("...b...", excerpt("abc", "b", radius: 0)) + assert_equal("abc", excerpt("abc", "b", radius: 1)) + assert_equal("abc...", excerpt("abcd", "b", radius: 1)) + assert_equal("...abc", excerpt("zabc", "b", radius: 1)) + assert_equal("...abc...", excerpt("zabcd", "b", radius: 1)) + assert_equal("zabcd", excerpt("zabcd", "b", radius: 2)) # excerpt strips the resulting string before ap-/prepending excerpt_string. # whether this behavior is meaningful when excerpt_string is not to be # appended is questionable. - assert_equal("zabcd", excerpt(" zabcd ", "b", :radius => 4)) - assert_equal("...abc...", excerpt("z abc d", "b", :radius => 1)) + assert_equal("zabcd", excerpt(" zabcd ", "b", radius: 4)) + assert_equal("...abc...", excerpt("z abc d", "b", radius: 1)) end def test_excerpt_with_omission - assert_equal("[...]is a beautiful morn[...]", excerpt("This is a beautiful morning", "beautiful", :omission => "[...]",:radius => 5)) + assert_equal("[...]is a beautiful morn[...]", excerpt("This is a beautiful morning", "beautiful", omission: "[...]", radius: 5)) assert_equal( "This is the ultimate supercalifragilisticexpialidoceous very looooooooooooooooooong looooooooooooong beautiful morning with amazing sunshine and awesome tempera[...]", excerpt("This is the ultimate supercalifragilisticexpialidoceous very looooooooooooooooooong looooooooooooong beautiful morning with amazing sunshine and awesome temperatures. So what are you gonna do about it?", "very", - :omission => "[...]") + omission: "[...]") ) end def test_excerpt_with_utf8 - assert_equal("...\357\254\203ciency could not be...".force_encoding(Encoding::UTF_8), excerpt("That's why e\357\254\203ciency could not be helped".force_encoding(Encoding::UTF_8), 'could', :radius => 8)) + assert_equal("...\357\254\203ciency could not be...".dup.force_encoding(Encoding::UTF_8), excerpt("That's why e\357\254\203ciency could not be helped".dup.force_encoding(Encoding::UTF_8), "could", radius: 8)) end def test_excerpt_does_not_modify_the_options_hash - options = { :omission => "[...]",:radius => 5 } + options = { omission: "[...]", radius: 5 } passed_options = options.dup excerpt("This is a beautiful morning", "beautiful", passed_options) assert_equal options, passed_options end def test_excerpt_with_separator - options = { :separator => ' ', :radius => 1 } - assert_equal('...a very beautiful...', excerpt('This is a very beautiful morning', 'very', options)) - assert_equal('This is...', excerpt('This is a very beautiful morning', 'this', options)) - assert_equal('...beautiful morning', excerpt('This is a very beautiful morning', 'morning', options)) + options = { separator: " ", radius: 1 } + assert_equal("...a very beautiful...", excerpt("This is a very beautiful morning", "very", options)) + assert_equal("This is...", excerpt("This is a very beautiful morning", "this", options)) + assert_equal("...beautiful morning", excerpt("This is a very beautiful morning", "morning", options)) - options = { :separator => "\n", :radius => 0 } - assert_equal("...very long...", excerpt("my very\nvery\nvery long\nstring", 'long', options)) + options = { separator: "\n", radius: 0 } + assert_equal("...very long...", excerpt("my very\nvery\nvery long\nstring", "long", options)) - options = { :separator => "\n", :radius => 1 } - assert_equal("...very\nvery long\nstring", excerpt("my very\nvery\nvery long\nstring", 'long', options)) + options = { separator: "\n", radius: 1 } + assert_equal("...very\nvery long\nstring", excerpt("my very\nvery\nvery long\nstring", "long", options)) - assert_equal excerpt('This is a beautiful morning', 'a'), - excerpt('This is a beautiful morning', 'a', separator: nil) + assert_equal excerpt("This is a beautiful morning", "a"), + excerpt("This is a beautiful morning", "a", separator: nil) end def test_word_wrap - assert_equal("my very very\nvery long\nstring", word_wrap("my very very very long string", :line_width => 15)) + assert_equal("my very very\nvery long\nstring", word_wrap("my very very very long string", line_width: 15)) end def test_word_wrap_with_extra_newlines - assert_equal("my very very\nvery long\nstring\n\nwith another\nline", word_wrap("my very very very long string\n\nwith another line", :line_width => 15)) + assert_equal("my very very\nvery long\nstring\n\nwith another\nline", word_wrap("my very very very long string\n\nwith another line", line_width: 15)) end def test_word_wrap_does_not_modify_the_options_hash - options = { :line_width => 15 } + options = { line_width: 15 } passed_options = options.dup word_wrap("some text", passed_options) assert_equal options, passed_options @@ -373,12 +375,14 @@ class TextHelperTest < ActionView::TestCase def test_pluralization assert_equal("1 count", pluralize(1, "count")) assert_equal("2 counts", pluralize(2, "count")) - assert_equal("1 count", pluralize('1', "count")) - assert_equal("2 counts", pluralize('2', "count")) - assert_equal("1,066 counts", pluralize('1,066', "count")) - assert_equal("1.25 counts", pluralize('1.25', "count")) - assert_equal("1.0 count", pluralize('1.0', "count")) - assert_equal("1.00 count", pluralize('1.00', "count")) + assert_equal("1 count", pluralize("1", "count")) + assert_equal("2 counts", pluralize("2", "count")) + assert_equal("1,066 counts", pluralize("1,066", "count")) + assert_equal("1.25 counts", pluralize("1.25", "count")) + assert_equal("1.0 count", pluralize("1.0", "count")) + assert_equal("1.00 count", pluralize("1.00", "count")) + assert_equal("2 counters", pluralize(2, "count", "counters")) + assert_equal("0 counters", pluralize(nil, "count", "counters")) assert_equal("2 counters", pluralize(2, "count", plural: "counters")) assert_equal("0 counters", pluralize(nil, "count", plural: "counters")) assert_equal("2 people", pluralize(2, "person")) @@ -394,7 +398,7 @@ class TextHelperTest < ActionView::TestCase I18n.locale = :de ActiveSupport::Inflector.inflections(:de) do |inflect| - inflect.irregular 'region', 'regionen' + inflect.irregular "region", "regionen" end assert_equal("1 region", pluralize(1, "region")) @@ -405,12 +409,6 @@ class TextHelperTest < ActionView::TestCase end end - def test_deprecated_plural_as_positional_argument - assert_deprecated do - pluralize(2, 'count', 'counters') - end - end - def test_cycle_class value = Cycle.new("one", 2, "3") assert_equal("one", value.to_s) @@ -458,29 +456,29 @@ class TextHelperTest < ActionView::TestCase end def test_named_cycles - assert_equal("1", cycle(1, 2, 3, :name => "numbers")) - assert_equal("red", cycle("red", "blue", :name => "colors")) - assert_equal("2", cycle(1, 2, 3, :name => "numbers")) - assert_equal("blue", cycle("red", "blue", :name => "colors")) - assert_equal("3", cycle(1, 2, 3, :name => "numbers")) - assert_equal("red", cycle("red", "blue", :name => "colors")) + assert_equal("1", cycle(1, 2, 3, name: "numbers")) + assert_equal("red", cycle("red", "blue", name: "colors")) + assert_equal("2", cycle(1, 2, 3, name: "numbers")) + assert_equal("blue", cycle("red", "blue", name: "colors")) + assert_equal("3", cycle(1, 2, 3, name: "numbers")) + assert_equal("red", cycle("red", "blue", name: "colors")) end def test_current_cycle_with_default_name - cycle("even","odd") + cycle("even", "odd") assert_equal "even", current_cycle - cycle("even","odd") + cycle("even", "odd") assert_equal "odd", current_cycle - cycle("even","odd") + cycle("even", "odd") assert_equal "even", current_cycle end def test_current_cycle_with_named_cycles - cycle("red", "blue", :name => "colors") + cycle("red", "blue", name: "colors") assert_equal "red", current_cycle("colors") - cycle("red", "blue", :name => "colors") + cycle("red", "blue", name: "colors") assert_equal "blue", current_cycle("colors") - cycle("red", "blue", :name => "colors") + cycle("red", "blue", name: "colors") assert_equal "red", current_cycle("colors") end @@ -490,19 +488,19 @@ class TextHelperTest < ActionView::TestCase end def test_current_cycle_with_more_than_two_names - cycle(1,2,3) + cycle(1, 2, 3) assert_equal "1", current_cycle - cycle(1,2,3) + cycle(1, 2, 3) assert_equal "2", current_cycle - cycle(1,2,3) + cycle(1, 2, 3) assert_equal "3", current_cycle - cycle(1,2,3) + cycle(1, 2, 3) assert_equal "1", current_cycle end def test_default_named_cycle assert_equal("1", cycle(1, 2, 3)) - assert_equal("2", cycle(1, 2, 3, :name => "default")) + assert_equal("2", cycle(1, 2, 3, name: "default")) assert_equal("3", cycle(1, 2, 3)) end @@ -518,13 +516,13 @@ class TextHelperTest < ActionView::TestCase end def test_reset_named_cycle - assert_equal("1", cycle(1, 2, 3, :name => "numbers")) - assert_equal("red", cycle("red", "blue", :name => "colors")) + assert_equal("1", cycle(1, 2, 3, name: "numbers")) + assert_equal("red", cycle("red", "blue", name: "colors")) reset_cycle("numbers") - assert_equal("1", cycle(1, 2, 3, :name => "numbers")) - assert_equal("blue", cycle("red", "blue", :name => "colors")) - assert_equal("2", cycle(1, 2, 3, :name => "numbers")) - assert_equal("red", cycle("red", "blue", :name => "colors")) + assert_equal("1", cycle(1, 2, 3, name: "numbers")) + assert_equal("blue", cycle("red", "blue", name: "colors")) + assert_equal("2", cycle(1, 2, 3, name: "numbers")) + assert_equal("red", cycle("red", "blue", name: "colors")) end def test_cycle_no_instance_variable_clashes diff --git a/actionview/test/template/text_test.rb b/actionview/test/template/text_test.rb index d899d54589..0c6470df21 100644 --- a/actionview/test/template/text_test.rb +++ b/actionview/test/template/text_test.rb @@ -1,17 +1,25 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" class TextTest < ActiveSupport::TestCase - test 'formats returns symbol for recognized MIME type' do - assert_equal [:text], ActionView::Template::Text.new('', :text).formats + test "formats always return :text" do + assert_equal [:text], ActionView::Template::Text.new("").formats + end + + test "identifier should return 'text template'" do + assert_equal "text template", ActionView::Template::Text.new("").identifier + end + + test "inspect should return 'text template'" do + assert_equal "text template", ActionView::Template::Text.new("").inspect end - test 'formats returns string for recognized MIME type when MIME does not have symbol' do - foo = Mime::Type.lookup("foo") - assert_nil foo.to_sym - assert_equal ['foo'], ActionView::Template::Text.new('', foo).formats + test "to_str should return a given string" do + assert_equal "a cat", ActionView::Template::Text.new("a cat").to_str end - test 'formats returns string for unknown MIME type' do - assert_equal ['foo'], ActionView::Template::Text.new('', 'foo').formats + test "render should return a given string" do + assert_equal "a dog", ActionView::Template::Text.new("a dog").render end end diff --git a/actionview/test/template/translation_helper_test.rb b/actionview/test/template/translation_helper_test.rb index 38b9284767..8956a584ff 100644 --- a/actionview/test/template/translation_helper_test.rb +++ b/actionview/test/template/translation_helper_test.rb @@ -1,9 +1,11 @@ -require 'abstract_unit' +# frozen_string_literal: true + +require "abstract_unit" module I18n class CustomExceptionHandler def self.call(exception, locale, key, options) - 'from CustomExceptionHandler' + "from CustomExceptionHandler" end end end @@ -15,22 +17,22 @@ class TranslationHelperTest < ActiveSupport::TestCase setup do I18n.backend.store_translations(:en, - :translations => { - :templates => { - :found => { :foo => 'Foo' }, - :array => { :foo => { :bar => 'Foo Bar' } }, - :default => { :foo => 'Foo' } + translations: { + templates: { + found: { foo: "Foo" }, + array: { foo: { bar: "Foo Bar" } }, + default: { foo: "Foo" } }, - :foo => 'Foo', - :hello => '<a>Hello World</a>', - :html => '<a>Hello World</a>', - :hello_html => '<a>Hello World</a>', - :interpolated_html => '<a>Hello %{word}</a>', - :array_html => %w(foo bar), - :array => %w(foo bar), - :count_html => { - :one => '<a>One %{count}</a>', - :other => '<a>Other %{count}</a>' + foo: "Foo", + hello: "<a>Hello World</a>", + html: "<a>Hello World</a>", + hello_html: "<a>Hello World</a>", + interpolated_html: "<a>Hello %{word}</a>", + array_html: %w(foo bar), + array: %w(foo bar), + count_html: { + one: "<a>One %{count}</a>", + other: "<a>Other %{count}</a>" } } ) @@ -42,8 +44,8 @@ class TranslationHelperTest < ActiveSupport::TestCase end def test_delegates_setting_to_i18n - assert_called_with(I18n, :translate, [:foo, :locale => 'en', :raise => true], returns: "") do - translate :foo, :locale => 'en' + assert_called_with(I18n, :translate, [:foo, locale: "en", raise: true], returns: "") do + translate :foo, locale: "en" end end @@ -58,7 +60,7 @@ class TranslationHelperTest < ActiveSupport::TestCase old_value = ActionView::Base.debug_missing_translation ActionView::Base.debug_missing_translation = false - expected = 'translation missing: en.translations.missing' + expected = "translation missing: en.translations.missing" assert_equal expected, translate(:"translations.missing") ensure ActionView::Base.debug_missing_translation = old_value @@ -78,10 +80,10 @@ class TranslationHelperTest < ActiveSupport::TestCase def test_returns_missing_translation_message_does_filters_out_i18n_options expected = '<span class="translation_missing" title="translation missing: en.translations.missing, year: 2015">Missing</span>' - assert_equal expected, translate(:"translations.missing", year: '2015', default: []) + assert_equal expected, translate(:"translations.missing", year: "2015", default: []) expected = '<span class="translation_missing" title="translation missing: en.scoped.translations.missing, year: 2015">Missing</span>' - assert_equal expected, translate(:"translations.missing", year: '2015', scope: %i(scoped)) + assert_equal expected, translate(:"translations.missing", year: "2015", scope: %i(scoped)) end def test_raises_missing_translation_message_with_raise_config_option @@ -96,14 +98,14 @@ class TranslationHelperTest < ActiveSupport::TestCase def test_raises_missing_translation_message_with_raise_option assert_raise(I18n::MissingTranslationData) do - translate(:"translations.missing", :raise => true) + translate(:"translations.missing", raise: true) end end 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) + assert_equal "from CustomExceptionHandler", translate(:"translations.missing", raise: false) ensure I18n.exception_handler = old_exception_handler end @@ -111,7 +113,7 @@ class TranslationHelperTest < ActiveSupport::TestCase 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) + assert_equal "from CustomExceptionHandler", translate(:"translations.missing_html", raise: false) ensure I18n.exception_handler = old_exception_handler end @@ -122,20 +124,20 @@ class TranslationHelperTest < ActiveSupport::TestCase end def test_finds_translation_scoped_by_partial - assert_equal 'Foo', view.render(:file => 'translations/templates/found').strip + assert_equal "Foo", view.render(file: "translations/templates/found").strip end def test_finds_array_of_translations_scoped_by_partial - assert_equal 'Foo Bar', @view.render(:file => 'translations/templates/array').strip + assert_equal "Foo Bar", @view.render(file: "translations/templates/array").strip end def test_default_lookup_scoped_by_partial - assert_equal 'Foo', view.render(:file => 'translations/templates/default').strip + assert_equal "Foo", view.render(file: "translations/templates/default").strip end def test_missing_translation_scoped_by_partial expected = '<span class="translation_missing" title="translation missing: en.translations.templates.missing.missing">Missing</span>' - assert_equal expected, view.render(:file => 'translations/templates/missing').strip + assert_equal expected, view.render(file: "translations/templates/missing").strip end def test_translate_does_not_mark_plain_text_as_safe_html @@ -152,14 +154,14 @@ class TranslationHelperTest < ActiveSupport::TestCase 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 => word_struct.new("<World>")) + assert_equal "<a>Hello <World></a>", translate(:'translations.interpolated_html', word: "<World>") + assert_equal "<a>Hello <World></a>", translate(:'translations.interpolated_html', word: word_struct.new("<World>")) end def test_translate_with_html_count - assert_equal '<a>One 1</a>', translate(:'translations.count_html', :count => 1) - assert_equal '<a>Other 2</a>', translate(:'translations.count_html', :count => 2) - assert_equal '<a>Other <One></a>', translate(:'translations.count_html', :count => '<One>') + assert_equal "<a>One 1</a>", translate(:'translations.count_html', count: 1) + assert_equal "<a>Other 2</a>", translate(:'translations.count_html', count: 2) + assert_equal "<a>Other <One></a>", translate(:'translations.count_html', count: "<One>") end def test_translation_returning_an_array_ignores_html_suffix @@ -167,13 +169,13 @@ class TranslationHelperTest < ActiveSupport::TestCase end def test_translate_with_default_named_html - translation = translate(:'translations.missing', :default => :'translations.hello_html') - assert_equal '<a>Hello World</a>', translation + translation = translate(:'translations.missing', default: :'translations.hello_html') + assert_equal "<a>Hello World</a>", translation assert_equal true, translation.html_safe? end def test_translate_with_missing_default - translation = translate(:'translations.missing', :default => :'translations.missing_html') + 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? @@ -181,31 +183,31 @@ class TranslationHelperTest < ActiveSupport::TestCase def test_translate_with_missing_default_and_raise_option assert_raise(I18n::MissingTranslationData) do - translate(:'translations.missing', :default => :'translations.missing_html', :raise => true) + 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 + translation = translate(:'translations.missing', default: [:'translations.missing_html', :'translations.hello_html']) + assert_equal "<a>Hello World</a>", translation assert_equal true, translation.html_safe? end def test_translate_with_last_default_named_html - translation = translate(:'translations.missing', :default => [:'translations.missing', :'translations.hello_html']) - assert_equal '<a>Hello World</a>', translation + translation = translate(:'translations.missing', default: [:'translations.missing', :'translations.hello_html']) + assert_equal "<a>Hello World</a>", translation 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 + 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 + translation = translate(:'translations.missing', default: "A Generic String") + assert_equal "A Generic String", translation end def test_translate_with_object_default @@ -214,13 +216,13 @@ class TranslationHelperTest < ActiveSupport::TestCase 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 + 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 + 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 diff --git a/actionview/test/template/url_helper_test.rb b/actionview/test/template/url_helper_test.rb index ab56d80de3..0cd0386cac 100644 --- a/actionview/test/template/url_helper_test.rb +++ b/actionview/test/template/url_helper_test.rb @@ -1,15 +1,15 @@ -require 'abstract_unit' +# frozen_string_literal: true -class UrlHelperTest < ActiveSupport::TestCase +require "abstract_unit" +class UrlHelperTest < ActiveSupport::TestCase # In a few cases, the helper proxies to 'controller' # or request. # # In those cases, we'll set up a simple mock attr_accessor :controller, :request - cattr_accessor :request_forgery - self.request_forgery = false + cattr_accessor :request_forgery, default: false routes = ActionDispatch::Routing::RouteSet.new routes.draw do @@ -17,6 +17,10 @@ class UrlHelperTest < ActiveSupport::TestCase get "/other" => "foo#other" get "/article/:id" => "foo#article", :as => :article get "/category/:category" => "foo#category" + + scope :engine do + get "/" => "foo#bar" + end end include ActionView::Helpers::UrlHelper @@ -43,59 +47,59 @@ class UrlHelperTest < ActiveSupport::TestCase end def test_url_for_with_back - referer = 'http://www.example.com/referer' + referer = "http://www.example.com/referer" @controller = Struct.new(:request).new(Struct.new(:env).new("HTTP_REFERER" => referer)) - assert_equal 'http://www.example.com/referer', url_for(:back) + assert_equal "http://www.example.com/referer", url_for(:back) end def test_url_for_with_back_and_no_referer @controller = Struct.new(:request).new(Struct.new(:env).new({})) - assert_equal 'javascript:history.back()', url_for(:back) + assert_equal "javascript:history.back()", url_for(:back) end def test_url_for_with_back_and_no_controller @controller = nil - assert_equal 'javascript:history.back()', url_for(:back) + assert_equal "javascript:history.back()", url_for(:back) end def test_url_for_with_back_and_javascript_referer - referer = 'javascript:alert(document.cookie)' + referer = "javascript:alert(document.cookie)" @controller = Struct.new(:request).new(Struct.new(:env).new("HTTP_REFERER" => referer)) - assert_equal 'javascript:history.back()', url_for(:back) + assert_equal "javascript:history.back()", url_for(:back) end def test_url_for_with_invalid_referer - referer = 'THIS IS NOT A URL' + referer = "THIS IS NOT A URL" @controller = Struct.new(:request).new(Struct.new(:env).new("HTTP_REFERER" => referer)) - assert_equal 'javascript:history.back()', url_for(:back) + assert_equal "javascript:history.back()", url_for(:back) end def test_to_form_params_with_hash assert_equal( - [{ name: :name, value: 'David' }, { name: :nationality, value: 'Danish' }], - to_form_params(name: 'David', nationality: 'Danish') + [{ name: :name, value: "David" }, { name: :nationality, value: "Danish" }], + to_form_params(name: "David", nationality: "Danish") ) end def test_to_form_params_with_nested_hash assert_equal( - [{ name: 'country[name]', value: 'Denmark' }], - to_form_params(country: { name: 'Denmark' }) + [{ name: "country[name]", value: "Denmark" }], + to_form_params(country: { name: "Denmark" }) ) end def test_to_form_params_with_array_nested_in_hash assert_equal( - [{ name: 'countries[]', value: 'Denmark' }, { name: 'countries[]', value: 'Sweden' }], - to_form_params(countries: ['Denmark', 'Sweden']) + [{ name: "countries[]", value: "Denmark" }, { name: "countries[]", value: "Sweden" }], + to_form_params(countries: ["Denmark", "Sweden"]) ) end def test_to_form_params_with_namespace assert_equal( - [{ name: 'country[name]', value: 'Denmark' }], - to_form_params({name: 'Denmark'}, 'country') + [{ name: "country[name]", value: "Denmark" }], + to_form_params({ name: "Denmark" }, "country") ) end @@ -122,11 +126,11 @@ class UrlHelperTest < ActiveSupport::TestCase end def test_button_to_with_form_class - assert_dom_equal %{<form method="post" action="http://www.example.com" class="custom-class"><input type="submit" value="Hello" /></form>}, button_to("Hello", "http://www.example.com", form_class: 'custom-class') + assert_dom_equal %{<form method="post" action="http://www.example.com" class="custom-class"><input type="submit" value="Hello" /></form>}, button_to("Hello", "http://www.example.com", form_class: "custom-class") end def test_button_to_with_form_class_escapes - assert_dom_equal %{<form method="post" action="http://www.example.com" class="<script>evil_js</script>"><input type="submit" value="Hello" /></form>}, button_to("Hello", "http://www.example.com", form_class: '<script>evil_js</script>') + assert_dom_equal %{<form method="post" action="http://www.example.com" class="<script>evil_js</script>"><input type="submit" value="Hello" /></form>}, button_to("Hello", "http://www.example.com", form_class: "<script>evil_js</script>") end def test_button_to_with_query @@ -211,7 +215,7 @@ class UrlHelperTest < ActiveSupport::TestCase def test_button_to_with_block assert_dom_equal( %{<form method="post" action="http://www.example.com" class="button_to"><button type="submit"><span>Hello</span></button></form>}, - button_to("http://www.example.com") { content_tag(:span, 'Hello') } + button_to("http://www.example.com") { content_tag(:span, "Hello") } ) end @@ -222,17 +226,48 @@ class UrlHelperTest < ActiveSupport::TestCase ) end + class FakeParams + def initialize(permitted = true) + @permitted = permitted + end + + def permitted? + @permitted + end + + def to_h + if permitted? + { foo: :bar, baz: "quux" } + else + raise ArgumentError + end + end + end + + def test_button_to_with_permitted_strong_params + assert_dom_equal( + %{<form action="http://www.example.com" class="button_to" method="post"><input type="submit" value="Hello" /><input type="hidden" name="baz" value="quux" /><input type="hidden" name="foo" value="bar" /></form>}, + button_to("Hello", "http://www.example.com", params: FakeParams.new) + ) + end + + def test_button_to_with_unpermitted_strong_params + assert_raises(ArgumentError) do + button_to("Hello", "http://www.example.com", params: FakeParams.new(false)) + end + end + def test_button_to_with_nested_hash_params assert_dom_equal( %{<form action="http://www.example.com" class="button_to" method="post"><input type="submit" value="Hello" /><input type="hidden" name="foo[bar]" value="baz" /></form>}, - button_to("Hello", "http://www.example.com", params: { foo: { bar: 'baz' } }) + button_to("Hello", "http://www.example.com", params: { foo: { bar: "baz" } }) ) end def test_button_to_with_nested_array_params assert_dom_equal( %{<form action="http://www.example.com" class="button_to" method="post"><input type="submit" value="Hello" /><input type="hidden" name="foo[]" value="bar" /></form>}, - button_to("Hello", "http://www.example.com", params: { foo: ['bar'] }) + button_to("Hello", "http://www.example.com", params: { foo: ["bar"] }) ) end @@ -241,13 +276,13 @@ class UrlHelperTest < ActiveSupport::TestCase end def test_link_tag_without_host_option - assert_dom_equal(%{<a href="/">Test Link</a>}, link_to('Test Link', url_hash)) + assert_dom_equal(%{<a href="/">Test Link</a>}, link_to("Test Link", url_hash)) end def test_link_tag_with_host_option hash = hash_for(host: "www.example.com") expected = %{<a href="http://www.example.com/">Test Link</a>} - assert_dom_equal(expected, link_to('Test Link', hash)) + assert_dom_equal(expected, link_to("Test Link", hash)) end def test_link_tag_with_query @@ -261,15 +296,15 @@ class UrlHelperTest < ActiveSupport::TestCase end def test_link_tag_with_back - env = {"HTTP_REFERER" => "http://www.example.com/referer"} + env = { "HTTP_REFERER" => "http://www.example.com/referer" } @controller = Struct.new(:request).new(Struct.new(:env).new(env)) expected = %{<a href="#{env["HTTP_REFERER"]}">go back</a>} - assert_dom_equal expected, link_to('go back', :back) + assert_dom_equal expected, link_to("go back", :back) end def test_link_tag_with_back_and_no_referer @controller = Struct.new(:request).new(Struct.new(:env).new({})) - link = link_to('go back', :back) + link = link_to("go back", :back) assert_dom_equal %{<a href="javascript:history.back()">go back</a>}, link end @@ -329,7 +364,7 @@ class UrlHelperTest < ActiveSupport::TestCase def test_link_to_with_string_remote_in_non_html_options assert_dom_equal( %{<a href="/" data-remote="true">Hello</a>}, - link_to("Hello", hash_for('remote' => true), {}) + link_to("Hello", hash_for("remote" => true), {}) ) end @@ -350,14 +385,14 @@ class UrlHelperTest < ActiveSupport::TestCase def test_link_tag_using_delete_javascript_and_href assert_dom_equal( %{<a href="\#" rel="nofollow" data-method="delete">Destroy</a>}, - link_to("Destroy", "http://www.example.com", method: :delete, href: '#') + link_to("Destroy", "http://www.example.com", method: :delete, href: "#") ) end def test_link_tag_using_post_javascript_and_rel assert_dom_equal( %{<a href="http://www.example.com" data-method="post" rel="example nofollow">Hello</a>}, - link_to("Hello", "http://www.example.com", method: :post, rel: 'example') + link_to("Hello", "http://www.example.com", method: :post, rel: "example") ) end @@ -371,24 +406,24 @@ class UrlHelperTest < ActiveSupport::TestCase def test_link_tag_using_delete_javascript_and_href_and_confirm assert_dom_equal( %{<a href="\#" rel="nofollow" data-confirm="Are you serious?" data-method="delete">Destroy</a>}, - link_to("Destroy", "http://www.example.com", method: :delete, href: '#', data: { confirm: "Are you serious?" }) + link_to("Destroy", "http://www.example.com", method: :delete, href: "#", data: { confirm: "Are you serious?" }) ) end def test_link_tag_with_block assert_dom_equal %{<a href="/"><span>Example site</span></a>}, - link_to('/') { content_tag(:span, 'Example site') } + link_to("/") { content_tag(:span, "Example site") } end def test_link_tag_with_block_and_html_options assert_dom_equal %{<a class="special" href="/"><span>Example site</span></a>}, - link_to('/', class: "special") { content_tag(:span, 'Example site') } + link_to("/", class: "special") { content_tag(:span, "Example site") } end def test_link_tag_using_block_and_hash assert_dom_equal( %{<a href="/"><span>Example site</span></a>}, - link_to(url_hash) { content_tag(:span, 'Example site') } + link_to(url_hash) { content_tag(:span, "Example site") } ) end @@ -452,7 +487,7 @@ class UrlHelperTest < ActiveSupport::TestCase end def test_current_page_with_http_head_method - @request = request_for_url("/", :method => :head) + @request = request_for_url("/", method: :head) assert current_page?(url_hash) assert current_page?("http://www.example.com/") end @@ -470,6 +505,21 @@ class UrlHelperTest < ActiveSupport::TestCase assert current_page?("http://www.example.com/") end + def test_current_page_considering_params + @request = request_for_url("/?order=desc&page=1") + + assert !current_page?(url_hash, check_parameters: true) + assert !current_page?(url_hash.merge(check_parameters: true)) + assert !current_page?(ActionController::Parameters.new(url_hash.merge(check_parameters: true)).permit!) + assert !current_page?("http://www.example.com/", check_parameters: true) + end + + def test_current_page_considering_params_when_options_does_not_respond_to_to_hash + @request = request_for_url("/?order=desc&page=1") + + assert !current_page?(:back, check_parameters: false) + end + def test_current_page_with_params_that_match @request = request_for_url("/?order=desc&page=1") @@ -477,22 +527,22 @@ class UrlHelperTest < ActiveSupport::TestCase assert current_page?("http://www.example.com/?order=desc&page=1") end - def test_current_page_with_not_get_verb - @request = request_for_url("/events", method: :post) + def test_current_page_with_scope_that_match + @request = request_for_url("/engine/") - assert !current_page?('/events') + assert current_page?("/engine") end def test_current_page_with_escaped_params @request = request_for_url("/category/administra%c3%a7%c3%a3o") - assert current_page?(controller: 'foo', action: 'category', category: 'administração') + assert current_page?(controller: "foo", action: "category", category: "administração") end def test_current_page_with_escaped_params_with_different_encoding @request = request_for_url("/") - @request.stub(:path, "/category/administra%c3%a7%c3%a3o".force_encoding(Encoding::ASCII_8BIT)) do - assert current_page?(:controller => 'foo', :action => 'category', category: 'administração') + @request.stub(:path, "/category/administra%c3%a7%c3%a3o".dup.force_encoding(Encoding::ASCII_8BIT)) do + assert current_page?(controller: "foo", action: "category", category: "administração") assert current_page?("http://www.example.com/category/administra%c3%a7%c3%a3o") end end @@ -500,7 +550,19 @@ class UrlHelperTest < ActiveSupport::TestCase def test_current_page_with_double_escaped_params @request = request_for_url("/category/administra%c3%a7%c3%a3o?callback_url=http%3a%2f%2fexample.com%2ffoo") - assert current_page?(controller: 'foo', action: 'category', category: 'administração', callback_url: 'http://example.com/foo') + assert current_page?(controller: "foo", action: "category", category: "administração", callback_url: "http://example.com/foo") + end + + def test_current_page_with_trailing_slash + @request = request_for_url("/posts") + + assert current_page?("/posts/") + end + + def test_current_page_with_not_get_verb + @request = request_for_url("/events", method: :post) + + assert !current_page?("/events") end def test_link_unless_current @@ -521,7 +583,7 @@ class UrlHelperTest < ActiveSupport::TestCase @request = request_for_url("/?order=desc&page=1") assert_equal "Showing", - link_to_unless_current("Showing", hash_for(order: 'desc', page: '1')) + link_to_unless_current("Showing", hash_for(order: "desc", page: "1")) assert_equal "Showing", link_to_unless_current("Showing", "http://www.example.com/?order=desc&page=1") @@ -564,8 +626,8 @@ class UrlHelperTest < ActiveSupport::TestCase 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") + %{<a href="mailto:%23%21%24%25%26%27%2A%2B-%2F%3D%3F%5E_%60%7B%7D%7C@example.org">#!$%&'*+-/=?^_`{}|@example.org</a>}, + mail_to("#!$%&'*+-/=?^_`{}|@example.org") ) end @@ -577,13 +639,13 @@ class UrlHelperTest < ActiveSupport::TestCase 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.") + mail_to("me@example.com", "My email", cc: "", bcc: "", subject: "This is an example email", body: "This is the body of the message.") ) end def test_mail_to_with_img assert_dom_equal %{<a href="mailto:feedback@example.com"><img src="/feedback.png" /></a>}, - mail_to('feedback@example.com', raw('<img src="/feedback.png" />')) + mail_to("feedback@example.com", raw('<img src="/feedback.png" />')) end def test_mail_to_with_html_safe_string @@ -606,22 +668,22 @@ class UrlHelperTest < ActiveSupport::TestCase def test_mail_to_with_block assert_dom_equal %{<a href="mailto:me@example.com"><span>Email me</span></a>}, - mail_to('me@example.com') { content_tag(:span, 'Email me') } + mail_to("me@example.com") { content_tag(:span, "Email me") } end def test_mail_to_with_block_and_options assert_dom_equal %{<a class="special" href="mailto:me@example.com?cc=ccaddress%40example.com"><span>Email me</span></a>}, - mail_to('me@example.com', cc: "ccaddress@example.com", class: "special") { content_tag(:span, 'Email me') } + mail_to("me@example.com", cc: "ccaddress@example.com", class: "special") { content_tag(:span, "Email me") } end def test_mail_to_does_not_modify_html_options_hash - options = { class: 'special' } - mail_to 'me@example.com', 'ME!', options - assert_equal({ class: 'special' }, options) + options = { class: "special" } + mail_to "me@example.com", "ME!", options + assert_equal({ class: "special" }, options) end def protect_against_forgery? - self.request_forgery + request_forgery end def form_authenticity_token(*args) @@ -631,46 +693,39 @@ class UrlHelperTest < ActiveSupport::TestCase def request_forgery_protection_token "form_token" end - - private - def sort_query_string_params(uri) - path, qs = uri.split('?') - qs = qs.split('&').sort.join('&') if qs - qs ? "#{path}?#{qs}" : path - end end class UrlHelperControllerTest < ActionController::TestCase class UrlHelperController < ActionController::Base test_routes do - get 'url_helper_controller_test/url_helper/show/:id', - to: 'url_helper_controller_test/url_helper#show', + get "url_helper_controller_test/url_helper/show/:id", + to: "url_helper_controller_test/url_helper#show", as: :show - get 'url_helper_controller_test/url_helper/profile/:name', - to: 'url_helper_controller_test/url_helper#show', + get "url_helper_controller_test/url_helper/profile/:name", + to: "url_helper_controller_test/url_helper#show", as: :profile - get 'url_helper_controller_test/url_helper/show_named_route', - to: 'url_helper_controller_test/url_helper#show_named_route', + get "url_helper_controller_test/url_helper/show_named_route", + to: "url_helper_controller_test/url_helper#show_named_route", as: :show_named_route ActiveSupport::Deprecation.silence do get "/:controller(/:action(/:id))" end - get 'url_helper_controller_test/url_helper/normalize_recall_params', + get "url_helper_controller_test/url_helper/normalize_recall_params", to: UrlHelperController.action(:normalize_recall), as: :normalize_recall_params - get '/url_helper_controller_test/url_helper/override_url_helper/default', - to: 'url_helper_controller_test/url_helper#override_url_helper', + get "/url_helper_controller_test/url_helper/override_url_helper/default", + to: "url_helper_controller_test/url_helper#override_url_helper", as: :override_url_helper end def show if params[:name] - render inline: 'ok' + render inline: "ok" else redirect_to profile_path(params[:id]) end @@ -685,23 +740,23 @@ class UrlHelperControllerTest < ActionController::TestCase end def nil_url_for - render inline: '<%= url_for(nil) %>' + render inline: "<%= url_for(nil) %>" end def normalize_recall_params - render inline: '<%= normalize_recall_params_path %>' + render inline: "<%= normalize_recall_params_path %>" end def recall_params_not_changed - render inline: '<%= url_for(action: :show_url_for) %>' + render inline: "<%= url_for(action: :show_url_for) %>" end def override_url_helper - render inline: '<%= override_url_helper_path %>' + render inline: "<%= override_url_helper_path %>" end def override_url_helper_path - '/url_helper_controller_test/url_helper/override_url_helper/override' + "/url_helper_controller_test/url_helper/override_url_helper/override" end helper_method :override_url_helper_path end @@ -710,58 +765,58 @@ class UrlHelperControllerTest < ActionController::TestCase def test_url_for_shows_only_path get :show_url_for - assert_equal '/url_helper_controller_test/url_helper/show_url_for', @response.body + assert_equal "/url_helper_controller_test/url_helper/show_url_for", @response.body end def test_named_route_url_shows_host_and_path - get :show_named_route, params: { kind: 'url' } - assert_equal 'http://test.host/url_helper_controller_test/url_helper/show_named_route', + 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, params: { kind: 'path' } - assert_equal '/url_helper_controller_test/url_helper/show_named_route', @response.body + get :show_named_route, params: { kind: "path" } + assert_equal "/url_helper_controller_test/url_helper/show_named_route", @response.body end def test_url_for_nil_returns_current_path get :nil_url_for - assert_equal '/url_helper_controller_test/url_helper/nil_url_for', @response.body + assert_equal "/url_helper_controller_test/url_helper/nil_url_for", @response.body end def test_named_route_should_show_host_and_path_using_controller_default_url_options class << @controller def default_url_options - { host: 'testtwo.host' } + { host: "testtwo.host" } end end - get :show_named_route, params: { kind: 'url' } - assert_equal 'http://testtwo.host/url_helper_controller_test/url_helper/show_named_route', @response.body + get :show_named_route, params: { kind: "url" } + assert_equal "http://testtwo.host/url_helper_controller_test/url_helper/show_named_route", @response.body end def test_recall_params_should_be_normalized get :normalize_recall_params - assert_equal '/url_helper_controller_test/url_helper/normalize_recall_params', @response.body + assert_equal "/url_helper_controller_test/url_helper/normalize_recall_params", @response.body end def test_recall_params_should_not_be_changed get :recall_params_not_changed - assert_equal '/url_helper_controller_test/url_helper/show_url_for', @response.body + assert_equal "/url_helper_controller_test/url_helper/show_url_for", @response.body end def test_recall_params_should_normalize_id - get :show, params: { 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 + assert_equal "http://test.host/url_helper_controller_test/url_helper/profile/123", @response.location - get :show, params: { name: '123' } - assert_equal 'ok', @response.body + get :show, params: { name: "123" } + assert_equal "ok", @response.body end def test_url_helper_can_be_overridden get :override_url_helper - assert_equal '/url_helper_controller_test/url_helper/override_url_helper/override', @response.body + assert_equal "/url_helper_controller_test/url_helper/override_url_helper/override", @response.body end end @@ -778,9 +833,9 @@ class TasksController < ActionController::Base render_default end - protected + private def render_default - render inline: "<%= link_to_unless_current('tasks', tasks_path) %>\n" + + render inline: "<%= link_to_unless_current('tasks', tasks_path) %>\n" \ "<%= link_to_unless_current('tasks', tasks_url) %>" end end @@ -835,6 +890,11 @@ class WorkshopsController < ActionController::Base @workshop = Workshop.new(params[:id]) render inline: "<%= url_for(@workshop) %>\n<%= link_to('Workshop', @workshop) %>" end + + def edit + @workshop = Workshop.new(params[:id]) + render inline: "<%= current_page?(@workshop) %>" + end end class SessionsController < ActionController::Base @@ -899,4 +959,11 @@ class PolymorphicControllerTest < ActionController::TestCase get :edit, params: { workshop_id: 1, id: 1, format: "json" } assert_equal %{/workshops/1/sessions/1.json\n<a href="/workshops/1/sessions/1.json">Session</a>}, @response.body end + + def test_current_page_when_options_does_not_respond_to_to_hash + @controller = WorkshopsController.new + + get :edit, params: { id: 1 } + assert_equal "false", @response.body + end end diff --git a/actionview/test/tmp/.gitkeep b/actionview/test/tmp/.keep index e69de29bb2..e69de29bb2 100644 --- a/actionview/test/tmp/.gitkeep +++ b/actionview/test/tmp/.keep diff --git a/actionview/test/ujs/.gitignore b/actionview/test/ujs/.gitignore new file mode 100644 index 0000000000..31dbbff57c --- /dev/null +++ b/actionview/test/ujs/.gitignore @@ -0,0 +1 @@ +/log diff --git a/actionview/test/ujs/config.ru b/actionview/test/ujs/config.ru new file mode 100644 index 0000000000..7cd3a16acb --- /dev/null +++ b/actionview/test/ujs/config.ru @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +$LOAD_PATH.unshift __dir__ +require "server" + +run UJS::Server diff --git a/actionview/test/ujs/public/test/.eslintrc.yml b/actionview/test/ujs/public/test/.eslintrc.yml new file mode 100644 index 0000000000..06d7dd36ea --- /dev/null +++ b/actionview/test/ujs/public/test/.eslintrc.yml @@ -0,0 +1,21 @@ +env: + browser: true +extends: eslint:recommended +rules: + no-undef: off + no-unused-vars: off + indent: off + linebreak-style: ['error', 'unix'] + quotes: ['error', 'single'] + semi: ['error', 'never'] + no-shadow: ['error'] # Prevent potential errors + no-console: 'off' + # styles + space-before-function-paren: ['error', 'never'] + space-before-blocks: 'error' + brace-style: ['error', '1tbs', { allowSingleLine: true }] + key-spacing: 'error' + array-bracket-spacing: 'error' + comma-spacing: 'error' + comma-dangle: 'off' + eol-last: 'error' diff --git a/actionview/test/ujs/public/test/call-ajax.js b/actionview/test/ujs/public/test/call-ajax.js new file mode 100644 index 0000000000..49e64cad5c --- /dev/null +++ b/actionview/test/ujs/public/test/call-ajax.js @@ -0,0 +1,27 @@ +(function() { + +module('call-ajax', { + setup: function() { + $('#qunit-fixture') + .append($('<a />', { href: '#' })) + } +}) + +asyncTest('call ajax without "ajax:beforeSend"', 1, function() { + + var link = $('#qunit-fixture a') + link.bindNative('click', function() { + Rails.ajax({ + type: 'get', + url: '/', + success: function() { + ok(true, 'calling request in ajax:success') + } + }) + }) + + link.triggerNative('click') + setTimeout(function() { start() }, 13) +}) + +})() diff --git a/actionview/test/ujs/public/test/call-remote-callbacks.js b/actionview/test/ujs/public/test/call-remote-callbacks.js new file mode 100644 index 0000000000..48763f6301 --- /dev/null +++ b/actionview/test/ujs/public/test/call-remote-callbacks.js @@ -0,0 +1,239 @@ +(function() { + +module('call-remote-callbacks', { + setup: function() { + $('#qunit-fixture').append($('<form />', { + action: '/echo', method: 'get', 'data-remote': 'true' + })) + }, + teardown: function() { + $(document).undelegate('form[data-remote]', 'ajax:beforeSend') + $(document).undelegate('form[data-remote]', 'ajax:before') + $(document).undelegate('form[data-remote]', 'ajax:send') + $(document).undelegate('form[data-remote]', 'ajax:complete') + $(document).undelegate('form[data-remote]', 'ajax:success') + $(document).unbind('iframe:loading') + } +}) + +function submit(fn) { + var form = $('form') + + if (fn) fn(form) + form.triggerNative('submit') + + setTimeout(function() { start() }, 13) +} + +asyncTest('modifying form fields with "ajax:before" sends modified data in request', 3, function() { + $('form[data-remote]') + .append($('<input type="text" name="user_name" value="john">')) + .append($('<input type="text" name="removed_user_name" value="john">')) + .bindNative('ajax:before', function() { + var form = $(this) + form + .append($('<input />', {name: 'other_user_name', value: 'jonathan'})) + .find('input[name="removed_user_name"]').remove() + form + .find('input[name="user_name"]').val('steve') + }) + + submit(function(form) { + form.bindNative('ajax:success', function(e, data, status, xhr) { + equal(data.params.user_name, 'steve', 'modified field value should have been submitted') + equal(data.params.other_user_name, 'jonathan', 'added field value should have been submitted') + equal(data.params.removed_user_name, undefined, 'removed field value should be undefined') + }) + }) +}) + +asyncTest('modifying data("type") with "ajax:before" requests new dataType in request', 1, function() { + $('form[data-remote]').data('type', 'html') + .bindNative('ajax:before', function() { + this.setAttribute('data-type', 'xml') + }) + + submit(function(form) { + form.bindNative('ajax:beforeSend', function(e, xhr, settings) { + equal(settings.dataType, 'xml', 'modified dataType should have been requested') + }) + }) +}) + +asyncTest('setting data("with-credentials",true) with "ajax:before" uses new setting in request', 1, function() { + $('form[data-remote]').data('with-credentials', false) + .bindNative('ajax:before', function() { + this.setAttribute('data-with-credentials', true) + }) + + submit(function(form) { + form.bindNative('ajax:beforeSend', function(e, xhr, settings) { + equal(settings.withCredentials, true, 'setting modified in ajax:before should have forced withCredentials request') + }) + }) +}) + +asyncTest('stopping the "ajax:beforeSend" event aborts the request', 1, function() { + submit(function(form) { + form.bindNative('ajax:beforeSend', function() { + ok(true, 'aborting request in ajax:beforeSend') + return false + }) + form.unbind('ajax:send').bindNative('ajax:send', function() { + ok(false, 'ajax:send should not run') + }) + form.bindNative('ajax:error', function(e, response, status, xhr) { + ok(false, 'ajax:error should not run') + }) + form.bindNative('ajax:complete', function() { + ok(false, 'ajax:complete should not run') + }) + }) +}) + +function skipIt() { + // This test cannot work due to the security feature in browsers which makes the value + // attribute of file input fields readonly, so it cannot be set with default value. + // This is what the test would look like though if browsers let us automate this test. + asyncTest('non-blank file form input field should abort remote request, but submit normally', 5, function() { + var form = $('form[data-remote]') + .append($('<input type="file" name="attachment" value="default.png">')) + .bindNative('ajax:beforeSend', function() { + ok(false, 'ajax:beforeSend should not run') + }) + .bind('iframe:loading', function() { + ok(true, 'form should get submitted') + }) + .bindNative('ajax:aborted:file', function(e, data) { + ok(data.length == 1, 'ajax:aborted:file event is passed all non-blank file inputs (jQuery objects)') + ok(data.first().is('input[name="attachment"]'), 'ajax:aborted:file adds non-blank file input to data') + ok(true, 'ajax:aborted:file event should run') + }) + .triggerNative('submit') + + setTimeout(function() { + form.find('input[type="file"]').val('') + form.unbind('ajax:beforeSend') + submit() + }, 13) + }) + + asyncTest('file form input field should not abort remote request if file form input does not have a name attribute', 5, function() { + var form = $('form[data-remote]') + .append($('<input type="file" value="default.png">')) + .bindNative('ajax:beforeSend', function() { + ok(true, 'ajax:beforeSend should run') + }) + .bind('iframe:loading', function() { + ok(true, 'form should get submitted') + }) + .bindNative('ajax:aborted:file', function(e, data) { + ok(false, 'ajax:aborted:file should not run') + }) + .triggerNative('submit') + + setTimeout(function() { + form.find('input[type="file"]').val('') + form.unbind('ajax:beforeSend') + submit() + }, 13) + }) + + asyncTest('blank file input field should abort request entirely if handler bound to "ajax:aborted:file" event that returns false', 1, function() { + var form = $('form[data-remote]') + .append($('<input type="file" name="attachment" value="default.png">')) + .bindNative('ajax:beforeSend', function() { + ok(false, 'ajax:beforeSend should not run') + }) + .bind('iframe:loading', function() { + ok(false, 'form should not get submitted') + }) + .bindNative('ajax:aborted:file', function() { + return false + }) + .triggerNative('submit') + + setTimeout(function() { + form.find('input[type="file"]').val('') + form.unbind('ajax:beforeSend') + submit() + }, 13) + }) +} + +asyncTest('"ajax:beforeSend" can be observed and stopped with event delegation', 1, function() { + $(document).delegate('form[data-remote]', 'ajax:beforeSend', function() { + ok(true, 'ajax:beforeSend observed with event delegation') + return false + }) + + submit(function(form) { + form.unbind('ajax:send').bindNative('ajax:send', function() { + ok(false, 'ajax:send should not run') + }) + form.bindNative('ajax:complete', function() { + ok(false, 'ajax:complete should not run') + }) + }) +}) + +asyncTest('"ajax:beforeSend", "ajax:send", "ajax:success" and "ajax:complete" are triggered', 8, function() { + submit(function(form) { + form.bindNative('ajax:beforeSend', function(e, xhr, settings) { + ok(xhr.setRequestHeader, 'first argument to "ajax:beforeSend" should be an XHR object') + equal(settings.url, '/echo', 'second argument to "ajax:beforeSend" should be a settings object') + }) + form.bindNative('ajax:send', function(e, xhr) { + ok(xhr.abort, 'first argument to "ajax:send" should be an XHR object') + }) + form.bindNative('ajax:success', function(e, data, status, xhr) { + ok(data.REQUEST_METHOD, 'first argument to ajax:success should be a data object') + equal(status, 'OK', 'second argument to ajax:success should be a status string') + ok(xhr.getResponseHeader, 'third argument to "ajax:success" should be an XHR object') + }) + form.bindNative('ajax:complete', function(e, xhr, status) { + ok(xhr.getResponseHeader, 'first argument to "ajax:complete" should be an XHR object') + equal(status, 'OK', 'second argument to ajax:complete should be a status string') + }) + }) +}) + +asyncTest('"ajax:beforeSend", "ajax:send", "ajax:error" and "ajax:complete" are triggered on error', 8, function() { + submit(function(form) { + form.attr('action', '/error') + form.bindNative('ajax:beforeSend', function(arg) { ok(true, 'ajax:beforeSend') }) + form.bindNative('ajax:send', function(arg) { ok(true, 'ajax:send') }) + form.bindNative('ajax:error', function(e, response, status, xhr) { + equal(response, '', 'first argument to ajax:error should be an HTTP status response') + equal(status, 'Forbidden', 'second argument to ajax:error should be a status string') + ok(xhr.getResponseHeader, 'third argument to "ajax:error" should be an XHR object') + // Opera returns "0" for HTTP code + equal(xhr.status, window.opera ? 0 : 403, 'status code should be 403') + }) + form.bindNative('ajax:complete', function(e, xhr, status) { + ok(xhr.getResponseHeader, 'first argument to "ajax:complete" should be an XHR object') + equal(status, 'Forbidden', 'second argument to ajax:complete should be a status string') + }) + }) +}) + +asyncTest('binding to ajax callbacks via .delegate() triggers handlers properly', 4, function() { + $(document) + .delegate('form[data-remote]', 'ajax:beforeSend', function() { + ok(true, 'ajax:beforeSend handler is triggered') + }) + .delegate('form[data-remote]', 'ajax:send', function() { + ok(true, 'ajax:send handler is triggered') + }) + .delegate('form[data-remote]', 'ajax:success', function() { + ok(true, 'ajax:success handler is triggered') + }) + .delegate('form[data-remote]', 'ajax:complete', function() { + ok(true, 'ajax:complete handler is triggered') + }) + $('form[data-remote]').triggerNative('submit') + + setTimeout(function() { start() }, 13) +}) + +})() diff --git a/actionview/test/ujs/public/test/call-remote.js b/actionview/test/ujs/public/test/call-remote.js new file mode 100644 index 0000000000..5932195363 --- /dev/null +++ b/actionview/test/ujs/public/test/call-remote.js @@ -0,0 +1,275 @@ +(function() { + +function buildForm(attrs) { + attrs = $.extend({ action: '/echo', 'data-remote': 'true' }, attrs) + + $('#qunit-fixture').append($('<form />', attrs)) + .find('form').append($('<input type="text" name="user_name" value="john">')) +} + +module('call-remote') + +function submit(fn) { + $('form') + .bindNative('ajax:success', fn) + .bindNative('ajax:complete', function() { start() }) + .triggerNative('submit') +} + +asyncTest('form method is read from "method" and not from "data-method"', 1, function() { + buildForm({ method: 'post', 'data-method': 'get' }) + + submit(function(e, data, status, xhr) { + App.assertPostRequest(data) + }) +}) + +asyncTest('form method is not read from "data-method" attribute in case of missing "method"', 1, function() { + buildForm({ 'data-method': 'put' }) + + submit(function(e, data, status, xhr) { + App.assertGetRequest(data) + }) +}) + +asyncTest('form method is read from submit button "formmethod" if submit is triggered by that button', 1, function() { + var submitButton = $('<input type="submit" formmethod="get">') + buildForm({ method: 'post' }) + + $('#qunit-fixture').find('form').append(submitButton) + .bindNative('ajax:success', function(e, data, status, xhr) { + App.assertGetRequest(data) + }) + .bindNative('ajax:complete', function() { start() }) + + submitButton.triggerNative('click') +}) + +asyncTest('form default method is GET', 1, function() { + buildForm() + + submit(function(e, data, status, xhr) { + App.assertGetRequest(data) + }) +}) + +asyncTest('form url is picked up from "action"', 1, function() { + buildForm({ method: 'post' }) + + submit(function(e, data, status, xhr) { + App.assertRequestPath(data, '/echo') + }) +}) + +asyncTest('form url is read from "action" not "href"', 1, function() { + buildForm({ method: 'post', href: '/echo2' }) + + submit(function(e, data, status, xhr) { + App.assertRequestPath(data, '/echo') + }) +}) + +asyncTest('form url is read from submit button "formaction" if submit is triggered by that button', 1, function() { + var submitButton = $('<input type="submit" formaction="/echo">') + buildForm({ method: 'post', href: '/echo2' }) + + $('#qunit-fixture').find('form').append(submitButton) + .bindNative('ajax:success', function(e, data, status, xhr) { + App.assertRequestPath(data, '/echo') + }) + .bindNative('ajax:complete', function() { start() }) + + submitButton.triggerNative('click') +}) + +asyncTest('prefer JS, but accept any format', 1, function() { + buildForm({ method: 'post' }) + + submit(function(e, data, status, xhr) { + var accept = data.HTTP_ACCEPT + ok(accept.match(/text\/javascript.+\*\/\*/), 'Accept: ' + accept) + }) +}) + +asyncTest('JS code should be executed', 1, function() { + buildForm({ method: 'post', 'data-type': 'script' }) + + $('form').append('<input type="text" name="content_type" value="text/javascript">') + $('form').append('<input type="text" name="content" value="ok(true, \'remote code should be run\')">') + + submit() +}) + +asyncTest('ecmascript code should be executed', 1, function() { + buildForm({ method: 'post', 'data-type': 'script' }) + + $('form').append('<input type="text" name="content_type" value="application/ecmascript">') + $('form').append('<input type="text" name="content" value="ok(true, \'remote code should be run\')">') + + submit() +}) + +asyncTest('execution of JS code does not modify current DOM', 1, function() { + var docLength, newDocLength + function getDocLength() { + return document.documentElement.outerHTML.length + } + + buildForm({ method: 'post', 'data-type': 'script' }) + + $('form').append('<input type="text" name="content_type" value="text/javascript">') + $('form').append('<input type="text" name="content" value="\'remote code should be run\'">') + + docLength = getDocLength() + + submit(function() { + newDocLength = getDocLength() + ok(docLength === newDocLength, 'executed JS should not present in the document') + }) +}) + +asyncTest('XML document should be parsed', 1, function() { + buildForm({ method: 'post', 'data-type': 'html' }) + + $('form').append('<input type="text" name="content_type" value="application/xml">') + $('form').append('<input type="text" name="content" value="<p>hello</p>">') + + submit(function(e, data, status, xhr) { + ok(data instanceof Document, 'returned data should be an XML document') + }) +}) + +asyncTest('accept application/json if "data-type" is json', 1, function() { + buildForm({ method: 'post', 'data-type': 'json' }) + + submit(function(e, data, status, xhr) { + equal(data.HTTP_ACCEPT, 'application/json, text/javascript, */*; q=0.01') + }) +}) + +asyncTest('allow empty "data-remote" attribute', 1, function() { + var form = $('#qunit-fixture').append($('<form action="/echo" data-remote />')).find('form') + + submit(function() { + ok(true, 'form with empty "data-remote" attribute is also allowed') + }) +}) + +asyncTest('query string in form action should be stripped in a GET request in normal submit', 1, function() { + buildForm({ action: '/echo?param1=abc', 'data-remote': 'false' }) + + $(document).one('iframe:loaded', function(e, data) { + equal(data.params.param1, undefined, '"param1" should not be passed to server') + start() + }) + + $('#qunit-fixture form').triggerNative('submit') +}) + +asyncTest('query string in form action should be stripped in a GET request in ajax submit', 1, function() { + buildForm({ action: '/echo?param1=abc' }) + + submit(function(e, data, status, xhr) { + equal(data.params.param1, undefined, '"param1" should not be passed to server') + }) +}) + +asyncTest('query string in form action should not be stripped in a POST request in normal submit', 1, function() { + buildForm({ action: '/echo?param1=abc', method: 'post', 'data-remote': 'false' }) + + $(document).one('iframe:loaded', function(e, data) { + equal(data.params.param1, 'abc', '"param1" should be passed to server') + start() + }) + + $('#qunit-fixture form').triggerNative('submit') +}) + +asyncTest('query string in form action should not be stripped in a POST request in ajax submit', 1, function() { + buildForm({ action: '/echo?param1=abc', method: 'post' }) + + submit(function(e, data, status, xhr) { + equal(data.params.param1, 'abc', '"param1" should be passed to server') + }) +}) + +asyncTest('allow empty form "action"', 1, function() { + var currentLocation, ajaxLocation + + buildForm({ action: '' }) + + $('#qunit-fixture').find('form') + .bindNative('ajax:beforeSend', function(e, xhr, settings) { + // Get current location (the same way jQuery does) + try { + currentLocation = location.href + } catch(err) { + currentLocation = document.createElement( 'a' ) + currentLocation.href = '' + currentLocation = currentLocation.href + } + currentLocation = currentLocation.replace(/\?.*$/, '') + + // Actual location (strip out settings.data that jQuery serializes and appends) + // HACK: can no longer use settings.data below to see what was appended to URL, as of + // jQuery 1.6.3 (see http://bugs.jquery.com/ticket/10202 and https://github.com/jquery/jquery/pull/544) + ajaxLocation = settings.url.replace('user_name=john', '').replace(/&$/, '').replace(/\?$/, '') + equal(ajaxLocation.match(/^(.*)/)[1], currentLocation, 'URL should be current page by default') + + // Prevent the request from actually getting sent to the current page and + // causing an error. + return false + }) + .triggerNative('submit') + + setTimeout(function() { start() }, 13) +}) + +asyncTest('sends CSRF token in custom header', 1, function() { + buildForm({ method: 'post' }) + $('#qunit-fixture').append('<meta name="csrf-token" content="cf50faa3fe97702ca1ae" />') + + submit(function(e, data, status, xhr) { + equal(data.HTTP_X_CSRF_TOKEN, 'cf50faa3fe97702ca1ae', 'X-CSRF-Token header should be sent') + }) +}) + +asyncTest('intelligently guesses crossDomain behavior when target URL has a different protocol and/or hostname', 1, function() { + + // Don't set data-cross-domain here, just set action to be a different domain than localhost + buildForm({ action: 'http://www.alfajango.com' }) + $('#qunit-fixture').append('<meta name="csrf-token" content="cf50faa3fe97702ca1ae" />') + + $('#qunit-fixture').find('form') + .bindNative('ajax:beforeSend', function(evt, req, settings) { + + equal(settings.crossDomain, true, 'crossDomain should be set to true') + + // prevent request from actually getting sent off-domain + return false + }) + .triggerNative('submit') + + setTimeout(function() { start() }, 13) +}) + +asyncTest('intelligently guesses crossDomain behavior when target URL consists of only a path', 1, function() { + + // Don't set data-cross-domain here, just set action to be a different domain than localhost + buildForm({ action: '/just/a/path' }) + $('#qunit-fixture').append('<meta name="csrf-token" content="cf50faa3fe97702ca1ae" />') + + $('#qunit-fixture').find('form') + .bindNative('ajax:beforeSend', function(evt, req, settings) { + + equal(settings.crossDomain, false, 'crossDomain should be set to false') + + // prevent request from actually getting sent off-domain + return false + }) + .triggerNative('submit') + + setTimeout(function() { start() }, 13) +}) + +})() diff --git a/actionview/test/ujs/public/test/csrf-refresh.js b/actionview/test/ujs/public/test/csrf-refresh.js new file mode 100644 index 0000000000..e302042542 --- /dev/null +++ b/actionview/test/ujs/public/test/csrf-refresh.js @@ -0,0 +1,24 @@ +(function() { + +module('csrf-refresh', {}) + +asyncTest('refresh all csrf tokens', 1, function() { + var correctToken = 'cf50faa3fe97702ca1ae' + + var form = $('<form />') + var input = $('<input>').attr({ type: 'hidden', name: 'authenticity_token', id: 'authenticity_token', value: 'foo' }) + input.appendTo(form) + + $('#qunit-fixture') + .append('<meta name="csrf-param" content="authenticity_token"/>') + .append('<meta name="csrf-token" content="' + correctToken + '"/>') + .append(form) + + $.rails.refreshCSRFTokens() + currentToken = $('#qunit-fixture #authenticity_token').val() + + start() + equal(currentToken, correctToken) +}) + +})() diff --git a/actionview/test/ujs/public/test/csrf-token.js b/actionview/test/ujs/public/test/csrf-token.js new file mode 100644 index 0000000000..388b40e057 --- /dev/null +++ b/actionview/test/ujs/public/test/csrf-token.js @@ -0,0 +1,27 @@ +(function() { + +module('csrf-token', {}) + +asyncTest('find csrf token', 1, function() { + var correctToken = 'cf50faa3fe97702ca1ae' + + $('#qunit-fixture').append('<meta name="csrf-token" content="' + correctToken + '"/>') + + currentToken = $.rails.csrfToken() + + start() + equal(currentToken, correctToken) +}) + +asyncTest('find csrf param', 1, function() { + var correctParam = 'authenticity_token' + + $('#qunit-fixture').append('<meta name="csrf-param" content="' + correctParam + '"/>') + + currentParam = $.rails.csrfParam() + + start() + equal(currentParam, correctParam) +}) + +})() diff --git a/actionview/test/ujs/public/test/data-confirm.js b/actionview/test/ujs/public/test/data-confirm.js new file mode 100644 index 0000000000..d1ea82ea7e --- /dev/null +++ b/actionview/test/ujs/public/test/data-confirm.js @@ -0,0 +1,316 @@ +module('data-confirm', { + setup: function() { + $('#qunit-fixture').append($('<a />', { + href: '/echo', + 'data-remote': 'true', + 'data-confirm': 'Are you absolutely sure?', + text: 'my social security number' + })) + + $('#qunit-fixture').append($('<button />', { + 'data-url': '/echo', + 'data-remote': 'true', + 'data-confirm': 'Are you absolutely sure?', + text: 'Click me' + })) + + $('#qunit-fixture').append($('<form />', { + id: 'confirm', + action: '/echo', + 'data-remote': 'true' + })) + + $('#qunit-fixture').append($('<input />', { + type: 'submit', + form: 'confirm', + 'data-confirm': 'Are you absolutely sure?' + })) + + $('#qunit-fixture').append($('<button />', { + type: 'submit', + form: 'confirm', + disabled: 'disabled', + 'data-confirm': 'Are you absolutely sure?' + })) + + this.windowConfirm = window.confirm + }, + teardown: function() { + window.confirm = this.windowConfirm + } +}) + +asyncTest('clicking on a link with data-confirm attribute. Confirm yes.', 6, function() { + var message + // auto-confirm: + window.confirm = function(msg) { message = msg; return true } + + $('a[data-confirm]') + .bindNative('confirm:complete', function(e, data) { + App.assertCallbackInvoked('confirm:complete') + ok(data == true, 'confirm:complete passes in confirm answer (true)') + }) + .bindNative('ajax:success', function(e, data, status, xhr) { + App.assertCallbackInvoked('ajax:success') + App.assertRequestPath(data, '/echo') + App.assertGetRequest(data) + + equal(message, 'Are you absolutely sure?') + start() + }) + .triggerNative('click') +}) + +asyncTest('clicking on a button with data-confirm attribute. Confirm yes.', 6, function() { + var message + // auto-confirm: + window.confirm = function(msg) { message = msg; return true } + + $('button[data-confirm]') + .bindNative('confirm:complete', function(e, data) { + App.assertCallbackInvoked('confirm:complete') + ok(data == true, 'confirm:complete passes in confirm answer (true)') + }) + .bindNative('ajax:success', function(e, data, status, xhr) { + App.assertCallbackInvoked('ajax:success') + App.assertRequestPath(data, '/echo') + App.assertGetRequest(data) + + equal(message, 'Are you absolutely sure?') + start() + }) + .triggerNative('click') +}) + +asyncTest('clicking on a link with data-confirm attribute. Confirm No.', 3, function() { + var message + // auto-decline: + window.confirm = function(msg) { message = msg; return false } + + $('a[data-confirm]') + .bindNative('confirm:complete', function(e, data) { + App.assertCallbackInvoked('confirm:complete') + ok(data == false, 'confirm:complete passes in confirm answer (false)') + }) + .bindNative('ajax:beforeSend', function(e, data, status, xhr) { + App.assertCallbackNotInvoked('ajax:beforeSend') + }) + .triggerNative('click') + + setTimeout(function() { + equal(message, 'Are you absolutely sure?') + start() + }, 50) +}) + +asyncTest('clicking on a button with data-confirm attribute. Confirm No.', 3, function() { + var message + // auto-decline: + window.confirm = function(msg) { message = msg; return false } + + $('button[data-confirm]') + .bindNative('confirm:complete', function(e, data) { + App.assertCallbackInvoked('confirm:complete') + ok(data == false, 'confirm:complete passes in confirm answer (false)') + }) + .bindNative('ajax:beforeSend', function(e, data, status, xhr) { + App.assertCallbackNotInvoked('ajax:beforeSend') + }) + .triggerNative('click') + + setTimeout(function() { + equal(message, 'Are you absolutely sure?') + start() + }, 50) +}) + +asyncTest('clicking on a button with data-confirm attribute. Confirm error.', 3, function() { + var message + // auto-decline: + window.confirm = function(msg) { message = msg; throw 'some random error' } + + $('button[data-confirm]') + .bindNative('confirm:complete', function(e, data) { + App.assertCallbackInvoked('confirm:complete') + ok(data == false, 'confirm:complete passes in confirm answer (false)') + }) + .bindNative('ajax:beforeSend', function(e, data, status, xhr) { + App.assertCallbackNotInvoked('ajax:beforeSend') + }) + .triggerNative('click') + + setTimeout(function() { + equal(message, 'Are you absolutely sure?') + start() + }, 50) +}) + +asyncTest('clicking on a submit button with form and data-confirm attributes. Confirm No.', 3, function() { + var message + // auto-decline: + window.confirm = function(msg) { message = msg; return false } + + $('input[type=submit][form]') + .bindNative('confirm:complete', function(e, data) { + App.assertCallbackInvoked('confirm:complete') + ok(data == false, 'confirm:complete passes in confirm answer (false)') + }) + .bindNative('ajax:beforeSend', function(e, data, status, xhr) { + App.assertCallbackNotInvoked('ajax:beforeSend') + }) + .triggerNative('click') + + setTimeout(function() { + equal(message, 'Are you absolutely sure?') + start() + }, 50) +}) + +asyncTest('binding to confirm event of a link and returning false', 1, function() { + // redefine confirm function so we can make sure it's not called + window.confirm = function(msg) { + ok(false, 'confirm dialog should not be called') + } + + $('a[data-confirm]') + .bindNative('confirm', function() { + App.assertCallbackInvoked('confirm') + return false + }) + .bindNative('confirm:complete', function() { + App.assertCallbackNotInvoked('confirm:complete') + }) + .triggerNative('click') + + setTimeout(function() { + start() + }, 50) +}) + +asyncTest('binding to confirm event of a button and returning false', 1, function() { + // redefine confirm function so we can make sure it's not called + window.confirm = function(msg) { + ok(false, 'confirm dialog should not be called') + } + + $('button[data-confirm]') + .bindNative('confirm', function() { + App.assertCallbackInvoked('confirm') + return false + }) + .bindNative('confirm:complete', function() { + App.assertCallbackNotInvoked('confirm:complete') + }) + .triggerNative('click') + + setTimeout(function() { + start() + }, 50) +}) + +asyncTest('binding to confirm:complete event of a link and returning false', 2, function() { + // auto-confirm: + window.confirm = function(msg) { + ok(true, 'confirm dialog should be called') + return true + } + + $('a[data-confirm]') + .bindNative('confirm:complete', function() { + App.assertCallbackInvoked('confirm:complete') + return false + }) + .bindNative('ajax:beforeSend', function() { + App.assertCallbackNotInvoked('ajax:beforeSend') + }) + .triggerNative('click') + + setTimeout(function() { + start() + }, 50) +}) + +asyncTest('binding to confirm:complete event of a button and returning false', 2, function() { + // auto-confirm: + window.confirm = function(msg) { + ok(true, 'confirm dialog should be called') + return true + } + + $('button[data-confirm]') + .bindNative('confirm:complete', function() { + App.assertCallbackInvoked('confirm:complete') + return false + }) + .bindNative('ajax:beforeSend', function() { + App.assertCallbackNotInvoked('ajax:beforeSend') + }) + .triggerNative('click') + + setTimeout(function() { + start() + }, 50) +}) + +asyncTest('a button inside a form only confirms once', 1, function() { + var confirmations = 0 + window.confirm = function(msg) { + confirmations++ + return true + } + + $('#qunit-fixture').append($('<form />').append($('<button />', { + 'data-remote': 'true', + 'data-confirm': 'Are you absolutely sure?', + text: 'Click me' + }))) + + $('form > button[data-confirm]').triggerNative('click') + + ok(confirmations === 1, 'confirmation counter should be 1, but it was ' + confirmations) + start() +}) + +asyncTest('clicking on the children of a link should also trigger a confirm', 6, function() { + var message + // auto-confirm: + window.confirm = function(msg) { message = msg; return true } + + $('a[data-confirm]') + .html('<strong>Click me</strong>') + .bindNative('confirm:complete', function(e, data) { + App.assertCallbackInvoked('confirm:complete') + ok(data == true, 'confirm:complete passes in confirm answer (true)') + }) + .bindNative('ajax:success', function(e, data, status, xhr) { + App.assertCallbackInvoked('ajax:success') + App.assertRequestPath(data, '/echo') + App.assertGetRequest(data) + + equal(message, 'Are you absolutely sure?') + start() + }) + .find('strong') + .triggerNative('click') +}) + +asyncTest('clicking on the children of a disabled button should not trigger a confirm.', 1, function() { + var message + // auto-decline: + window.confirm = function(msg) { message = msg; return false } + + $('button[data-confirm][disabled]') + .html('<strong>Click me</strong>') + .bindNative('confirm', function() { + App.assertCallbackNotInvoked('confirm') + }) + .find('strong') + .bindNative('click', function() { + App.assertCallbackInvoked('click') + }) + .triggerNative('click') + + setTimeout(function() { + start() + }, 50) +}) diff --git a/actionview/test/ujs/public/test/data-disable-with.js b/actionview/test/ujs/public/test/data-disable-with.js new file mode 100644 index 0000000000..b29cbbc867 --- /dev/null +++ b/actionview/test/ujs/public/test/data-disable-with.js @@ -0,0 +1,391 @@ +module('data-disable-with', { + setup: function() { + $('#qunit-fixture').append($('<form />', { + action: '/echo', + 'data-remote': 'true', + method: 'post' + })) + .find('form') + .append($('<input type="text" data-disable-with="processing ..." name="user_name" value="john" />')) + + $('#qunit-fixture').append($('<form />', { + action: '/echo', + method: 'post', + id: 'not_remote' + })) + .find('form:last') + // WEEIRDD: the form won't submit to an iframe if the button is name="submit" (??!) + .append($('<input type="submit" data-disable-with="submitting ..." name="submit2" value="Submit" />')) + + $('#qunit-fixture').append($('<a />', { + text: 'Click me', + href: '/echo', + 'data-disable-with': 'clicking...' + })) + + $('#qunit-fixture').append($('<input />', { + type: 'submit', + form: 'not_remote', + 'data-disable-with': 'form attr submitting', + name: 'submit3', + value: 'Form Attr Submit' + })) + + $('#qunit-fixture').append($('<button />', { + text: 'Click me', + 'data-remote': true, + 'data-url': '/echo', + 'data-disable-with': 'clicking...' + })) + }, + teardown: function() { + $(document).unbind('iframe:loaded') + } +}) + +asyncTest('form input field with "data-disable-with" attribute', 7, function() { + var form = $('form[data-remote]'), input = form.find('input[type=text]') + + App.checkEnabledState(input, 'john') + + form.bindNative('ajax:success', function(e, data) { + setTimeout(function() { + App.checkEnabledState(input, 'john') + equal(data.params.user_name, 'john') + start() + }, 13) + }) + form.triggerNative('submit') + + App.checkDisabledState(input, 'processing ...') +}) + +asyncTest('blank form input field with "data-disable-with" attribute', 7, function() { + var form = $('form[data-remote]'), input = form.find('input[type=text]') + + input.val('') + App.checkEnabledState(input, '') + + form.bindNative('ajax:success', function(e, data) { + setTimeout(function() { + App.checkEnabledState(input, '') + equal(data.params.user_name, '') + start() + }, 13) + }) + form.triggerNative('submit') + + App.checkDisabledState(input, 'processing ...') +}) + +asyncTest('form button with "data-disable-with" attribute', 6, function() { + var form = $('form[data-remote]'), button = $('<button data-disable-with="submitting ..." name="submit2">Submit</button>') + form.append(button) + + App.checkEnabledState(button, 'Submit') + + form.bindNative('ajax:success', function(e, data) { + setTimeout(function() { + App.checkEnabledState(button, 'Submit') + start() + }, 13) + }) + form.triggerNative('submit') + + App.checkDisabledState(button, 'submitting ...') +}) + +asyncTest('form input[type=submit][data-disable-with] disables', 6, function() { + var form = $('form:not([data-remote])'), input = form.find('input[type=submit]') + + App.checkEnabledState(input, 'Submit') + + $(document).bind('iframe:loaded', function(e, data) { + setTimeout(function() { + App.checkDisabledState(input, 'submitting ...') + start() + }, 30) + }) + form.triggerNative('submit') + + setTimeout(function() { + App.checkDisabledState(input, 'submitting ...') + }, 30) +}) + +test('form input[type=submit][data-disable-with] re-enables when `pageshow` event is triggered', function() { + var form = $('form:not([data-remote])'), input = form.find('input[type=submit]') + + App.checkEnabledState(input, 'Submit') + + // Emulate the disabled state without submitting the form at all, what is the + // state after going back on firefox after submitting a form. + // + // See https://github.com/rails/jquery-ujs/issues/357 + $.rails.disableElement(form[0]) + + App.checkDisabledState(input, 'submitting ...') + + $(window).triggerNative('pageshow') + + App.checkEnabledState(input, 'Submit') +}) + +asyncTest('form[data-remote] input[type=submit][data-disable-with] is replaced in ajax callback', 2, function() { + var form = $('form:not([data-remote])').attr('data-remote', 'true'), origFormContents = form.html() + + form.bindNative('ajax:success', function() { + form.html(origFormContents) + + setTimeout(function() { + var input = form.find('input[type=submit]') + App.checkEnabledState(input, 'Submit') + start() + }, 30) + }).triggerNative('submit') +}) + +asyncTest('form[data-remote] input[data-disable-with] is replaced with disabled field in ajax callback', 2, function() { + var form = $('form:not([data-remote])').attr('data-remote', 'true'), input = form.find('input[type=submit]'), + newDisabledInput = input.clone().attr('disabled', 'disabled') + + form.bindNative('ajax:success', function() { + input.replaceWith(newDisabledInput) + + setTimeout(function() { + App.checkEnabledState(newDisabledInput, 'Submit') + start() + }, 30) + }).triggerNative('submit') +}) + +asyncTest('form input[type=submit][data-disable-with] using "form" attribute disables', 6, function() { + var form = $('#not_remote'), input = $('input[form=not_remote]') + App.checkEnabledState(input, 'Form Attr Submit') + + $(document).bind('iframe:loaded', function(e, data) { + setTimeout(function() { + App.checkDisabledState(input, 'form attr submitting') + start() + }, 30) + }) + form.triggerNative('submit') + + setTimeout(function() { + App.checkDisabledState(input, 'form attr submitting') + }, 30) + +}) + +asyncTest('form[data-remote] textarea[data-disable-with] attribute', 3, function() { + var form = $('form[data-remote]'), + textarea = $('<textarea data-disable-with="processing ..." name="user_bio">born, lived, died.</textarea>').appendTo(form) + + form.bindNative('ajax:success', function(e, data) { + setTimeout(function() { + equal(data.params.user_bio, 'born, lived, died.') + start() + }, 13) + }) + form.triggerNative('submit') + + App.checkDisabledState(textarea, 'processing ...') +}) + +asyncTest('a[data-disable-with] disables', 4, function() { + var link = $('a[data-disable-with]') + + App.checkEnabledState(link, 'Click me') + + link.triggerNative('click') + App.checkDisabledState(link, 'clicking...') + start() +}) + +test('a[data-disable-with] re-enables when `pageshow` event is triggered', function() { + var link = $('a[data-disable-with]') + + App.checkEnabledState(link, 'Click me') + + link.triggerNative('click') + App.checkDisabledState(link, 'clicking...') + + $(window).triggerNative('pageshow') + App.checkEnabledState(link, 'Click me') +}) + +asyncTest('a[data-remote][data-disable-with] disables and re-enables', 6, function() { + var link = $('a[data-disable-with]').attr('data-remote', true) + + App.checkEnabledState(link, 'Click me') + + link + .bindNative('ajax:beforeSend', function() { + App.checkDisabledState(link, 'clicking...') + }) + .bindNative('ajax:complete', function() { + setTimeout( function() { + App.checkEnabledState(link, 'Click me') + start() + }, 15) + }) + .triggerNative('click') +}) + +asyncTest('a[data-remote][data-disable-with] re-enables when `ajax:before` event is cancelled', 6, function() { + var link = $('a[data-disable-with]').attr('data-remote', true) + + App.checkEnabledState(link, 'Click me') + + link + .bindNative('ajax:before', function() { + App.checkDisabledState(link, 'clicking...') + return false + }) + .triggerNative('click') + + setTimeout(function() { + App.checkEnabledState(link, 'Click me') + start() + }, 30) +}) + +asyncTest('a[data-remote][data-disable-with] re-enables when `ajax:beforeSend` event is cancelled', 6, function() { + var link = $('a[data-disable-with]').attr('data-remote', true) + + App.checkEnabledState(link, 'Click me') + + link + .bindNative('ajax:beforeSend', function() { + App.checkDisabledState(link, 'clicking...') + return false + }) + .triggerNative('click') + + setTimeout(function() { + App.checkEnabledState(link, 'Click me') + start() + }, 30) +}) + +asyncTest('a[data-remote][data-disable-with] re-enables when `ajax:error` event is triggered', 6, function() { + var link = $('a[data-disable-with]').attr('data-remote', true).attr('href', '/error') + + App.checkEnabledState(link, 'Click me') + + link + .bindNative('ajax:beforeSend', function() { + App.checkDisabledState(link, 'clicking...') + }) + .triggerNative('click') + + setTimeout(function() { + App.checkEnabledState(link, 'Click me') + start() + }, 30) +}) + +asyncTest('form[data-remote] input|button|textarea[data-disable-with] does not disable when `ajax:beforeSend` event is cancelled', 8, function() { + var form = $('form[data-remote]'), + input = form.find('input:text'), + button = $('<button data-disable-with="submitting ..." name="submit2">Submit</button>').appendTo(form), + textarea = $('<textarea data-disable-with="processing ..." name="user_bio">born, lived, died.</textarea>').appendTo(form), + submit = $('<input type="submit" data-disable-with="submitting ..." name="submit2" value="Submit" />').appendTo(form) + + form + .bindNative('ajax:beforeSend', function() { + return false + }) + .triggerNative('submit') + + App.checkEnabledState(input, 'john') + App.checkEnabledState(button, 'Submit') + App.checkEnabledState(textarea, 'born, lived, died.') + App.checkEnabledState(submit, 'Submit') + + start() +}) + +asyncTest('ctrl-clicking on a link does not disables the link', 6, function() { + var link = $('a[data-disable-with]') + + App.checkEnabledState(link, 'Click me') + + link.triggerNative('click', { metaKey: true }) + App.checkEnabledState(link, 'Click me') + + link.triggerNative('click', { metaKey: true }) + App.checkEnabledState(link, 'Click me') + start() +}) + +asyncTest('button[data-remote][data-disable-with] disables and re-enables', 6, function() { + var button = $('button[data-remote][data-disable-with]') + + App.checkEnabledState(button, 'Click me') + + button + .bindNative('ajax:send', function() { + App.checkDisabledState(button, 'clicking...') + }) + .bindNative('ajax:complete', function() { + setTimeout( function() { + App.checkEnabledState(button, 'Click me') + start() + }, 15) + }) + .triggerNative('click') +}) + +asyncTest('button[data-remote][data-disable-with] re-enables when `ajax:before` event is cancelled', 6, function() { + var button = $('button[data-remote][data-disable-with]') + + App.checkEnabledState(button, 'Click me') + + button + .bindNative('ajax:before', function() { + App.checkDisabledState(button, 'clicking...') + return false + }) + .triggerNative('click') + + setTimeout(function() { + App.checkEnabledState(button, 'Click me') + start() + }, 30) +}) + +asyncTest('button[data-remote][data-disable-with] re-enables when `ajax:beforeSend` event is cancelled', 6, function() { + var button = $('button[data-remote][data-disable-with]') + + App.checkEnabledState(button, 'Click me') + + button + .bindNative('ajax:beforeSend', function() { + App.checkDisabledState(button, 'clicking...') + return false + }) + .triggerNative('click') + + setTimeout(function() { + App.checkEnabledState(button, 'Click me') + start() + }, 30) +}) + +asyncTest('button[data-remote][data-disable-with] re-enables when `ajax:error` event is triggered', 6, function() { + var button = $('a[data-disable-with]').attr('data-remote', true).attr('href', '/error') + + App.checkEnabledState(button, 'Click me') + + button + .bindNative('ajax:send', function() { + App.checkDisabledState(button, 'clicking...') + }) + .triggerNative('click') + + setTimeout(function() { + App.checkEnabledState(button, 'Click me') + start() + }, 30) +}) diff --git a/actionview/test/ujs/public/test/data-disable.js b/actionview/test/ujs/public/test/data-disable.js new file mode 100644 index 0000000000..ccc38cf9ae --- /dev/null +++ b/actionview/test/ujs/public/test/data-disable.js @@ -0,0 +1,321 @@ +module('data-disable', { + setup: function() { + $('#qunit-fixture').append($('<form />', { + action: '/echo', + 'data-remote': 'true', + method: 'post' + })) + .find('form') + .append($('<input type="text" data-disable name="user_name" value="john" />')) + + $('#qunit-fixture').append($('<form />', { + action: '/echo', + method: 'post' + })) + .find('form:last') + // WEEIRDD: the form won't submit to an iframe if the button is name="submit" (??!) + .append($('<input type="submit" data-disable name="submit2" value="Submit" />')) + + $('#qunit-fixture').append($('<a />', { + text: 'Click me', + href: '/echo', + 'data-disable': 'true' + })) + + $('#qunit-fixture').append($('<button />', { + text: 'Click me', + 'data-remote': true, + 'data-url': '/echo', + 'data-disable': 'true' + })) + }, + teardown: function() { + $(document).unbind('iframe:loaded') + } +}) + +asyncTest('form input field with "data-disable" attribute', 7, function() { + var form = $('form[data-remote]'), input = form.find('input[type=text]') + + App.checkEnabledState(input, 'john') + + form.bindNative('ajax:success', function(e, data) { + setTimeout(function() { + App.checkEnabledState(input, 'john') + equal(data.params.user_name, 'john') + start() + }, 13) + }) + form.triggerNative('submit') + + App.checkDisabledState(input, 'john') +}) + +asyncTest('form button with "data-disable" attribute', 7, function() { + var form = $('form[data-remote]'), button = $('<button data-disable name="submit2">Submit</button>') + form.append(button) + + App.checkEnabledState(button, 'Submit') + + form.bindNative('ajax:success', function(e, data) { + setTimeout(function() { + App.checkEnabledState(button, 'Submit') + start() + }, 13) + }) + form.triggerNative('submit') + + App.checkDisabledState(button, 'Submit') + equal(button.data('ujs:enable-with'), undefined) +}) + +asyncTest('form input[type=submit][data-disable] disables', 6, function() { + var form = $('form:not([data-remote])'), input = form.find('input[type=submit]') + + App.checkEnabledState(input, 'Submit') + + // WEEIRDD: attaching this handler makes the test work in IE7 + $(document).bind('iframe:loading', function(e, f) {}) + + $(document).bind('iframe:loaded', function(e, data) { + setTimeout(function() { + App.checkDisabledState(input, 'Submit') + start() + }, 30) + }) + form.triggerNative('submit') + + setTimeout(function() { + App.checkDisabledState(input, 'Submit') + }, 30) +}) + +asyncTest('form[data-remote] input[type=submit][data-disable] is replaced in ajax callback', 2, function() { + var form = $('form:not([data-remote])').attr('data-remote', 'true'), origFormContents = form.html() + + form.bindNative('ajax:success', function() { + form.html(origFormContents) + + setTimeout(function() { + var input = form.find('input[type=submit]') + App.checkEnabledState(input, 'Submit') + start() + }, 30) + }).triggerNative('submit') +}) + +asyncTest('form[data-remote] input[data-disable] is replaced with disabled field in ajax callback', 2, function() { + var form = $('form:not([data-remote])').attr('data-remote', 'true'), input = form.find('input[type=submit]'), + newDisabledInput = input.clone().attr('disabled', 'disabled') + + form.bindNative('ajax:success', function() { + input.replaceWith(newDisabledInput) + + setTimeout(function() { + App.checkEnabledState(newDisabledInput, 'Submit') + start() + }, 30) + }).triggerNative('submit') +}) + +asyncTest('form[data-remote] textarea[data-disable] attribute', 3, function() { + var form = $('form[data-remote]'), + textarea = $('<textarea data-disable name="user_bio">born, lived, died.</textarea>').appendTo(form) + + form.bindNative('ajax:success', function(e, data) { + setTimeout(function() { + equal(data.params.user_bio, 'born, lived, died.') + start() + }, 13) + }) + form.triggerNative('submit') + + App.checkDisabledState(textarea, 'born, lived, died.') +}) + +asyncTest('a[data-disable] disables', 5, function() { + var link = $('a[data-disable]') + + App.checkEnabledState(link, 'Click me') + + link.triggerNative('click') + App.checkDisabledState(link, 'Click me') + equal(link.data('ujs:enable-with'), undefined) + start() +}) + +asyncTest('a[data-remote][data-disable] disables and re-enables', 6, function() { + var link = $('a[data-disable]').attr('data-remote', true) + + App.checkEnabledState(link, 'Click me') + + link + .bindNative('ajax:send', function() { + App.checkDisabledState(link, 'Click me') + }) + .bindNative('ajax:complete', function() { + setTimeout( function() { + App.checkEnabledState(link, 'Click me') + start() + }, 15) + }) + .triggerNative('click') +}) + +asyncTest('a[data-remote][data-disable] re-enables when `ajax:before` event is cancelled', 6, function() { + var link = $('a[data-disable]').attr('data-remote', true) + + App.checkEnabledState(link, 'Click me') + + link + .bindNative('ajax:before', function() { + App.checkDisabledState(link, 'Click me') + return false + }) + .triggerNative('click') + + setTimeout(function() { + App.checkEnabledState(link, 'Click me') + start() + }, 30) +}) + +asyncTest('a[data-remote][data-disable] re-enables when `ajax:beforeSend` event is cancelled', 6, function() { + var link = $('a[data-disable]').attr('data-remote', true) + + App.checkEnabledState(link, 'Click me') + + link + .bindNative('ajax:beforeSend', function() { + App.checkDisabledState(link, 'Click me') + return false + }) + .triggerNative('click') + + setTimeout(function() { + App.checkEnabledState(link, 'Click me') + start() + }, 30) +}) + +asyncTest('a[data-remote][data-disable] re-enables when `ajax:error` event is triggered', 6, function() { + var link = $('a[data-disable]').attr('data-remote', true).attr('href', '/error') + + App.checkEnabledState(link, 'Click me') + + link + .bindNative('ajax:send', function() { + App.checkDisabledState(link, 'Click me') + }) + .triggerNative('click') + + setTimeout(function() { + App.checkEnabledState(link, 'Click me') + start() + }, 30) +}) + +asyncTest('form[data-remote] input|button|textarea[data-disable] does not disable when `ajax:beforeSend` event is cancelled', 8, function() { + var form = $('form[data-remote]'), + input = form.find('input:text'), + button = $('<button data-disable="submitting ..." name="submit2">Submit</button>').appendTo(form), + textarea = $('<textarea data-disable name="user_bio">born, lived, died.</textarea>').appendTo(form), + submit = $('<input type="submit" data-disable="submitting ..." name="submit2" value="Submit" />').appendTo(form) + + form + .bindNative('ajax:beforeSend', function() { + return false + }) + .triggerNative('submit') + + App.checkEnabledState(input, 'john') + App.checkEnabledState(button, 'Submit') + App.checkEnabledState(textarea, 'born, lived, died.') + App.checkEnabledState(submit, 'Submit') + + start() +}) + +asyncTest('ctrl-clicking on a link does not disables the link', 6, function() { + var link = $('a[data-disable]') + + App.checkEnabledState(link, 'Click me') + + link.triggerNative('click', { metaKey: true }) + App.checkEnabledState(link, 'Click me') + + link.triggerNative('click', { ctrlKey: true }) + App.checkEnabledState(link, 'Click me') + start() +}) + +asyncTest('button[data-remote][data-disable] disables and re-enables', 6, function() { + var button = $('button[data-remote][data-disable]') + + App.checkEnabledState(button, 'Click me') + + button + .bindNative('ajax:send', function() { + App.checkDisabledState(button, 'Click me') + }) + .bindNative('ajax:complete', function() { + setTimeout( function() { + App.checkEnabledState(button, 'Click me') + start() + }, 15) + }) + .triggerNative('click') +}) + +asyncTest('button[data-remote][data-disable] re-enables when `ajax:before` event is cancelled', 6, function() { + var button = $('button[data-remote][data-disable]') + + App.checkEnabledState(button, 'Click me') + + button + .bindNative('ajax:before', function() { + App.checkDisabledState(button, 'Click me') + return false + }) + .triggerNative('click') + + setTimeout(function() { + App.checkEnabledState(button, 'Click me') + start() + }, 30) +}) + +asyncTest('button[data-remote][data-disable] re-enables when `ajax:beforeSend` event is cancelled', 6, function() { + var button = $('button[data-remote][data-disable]') + + App.checkEnabledState(button, 'Click me') + + button + .bindNative('ajax:beforeSend', function() { + App.checkDisabledState(button, 'Click me') + return false + }) + .triggerNative('click') + + setTimeout(function() { + App.checkEnabledState(button, 'Click me') + start() + }, 30) +}) + +asyncTest('button[data-remote][data-disable] re-enables when `ajax:error` event is triggered', 6, function() { + var button = $('a[data-disable]').attr('data-remote', true).attr('href', '/error') + + App.checkEnabledState(button, 'Click me') + + button + .bindNative('ajax:send', function() { + App.checkDisabledState(button, 'Click me') + }) + .triggerNative('click') + + setTimeout(function() { + App.checkEnabledState(button, 'Click me') + start() + }, 30) +}) diff --git a/actionview/test/ujs/public/test/data-method.js b/actionview/test/ujs/public/test/data-method.js new file mode 100644 index 0000000000..47d940c577 --- /dev/null +++ b/actionview/test/ujs/public/test/data-method.js @@ -0,0 +1,85 @@ +(function() { + +module('data-method', { + setup: function() { + $('#qunit-fixture').append($('<a />', { + href: '/echo', 'data-method': 'delete', text: 'destroy!' + })) + }, + teardown: function() { + $(document).unbind('iframe:loaded') + } +}) + +function submit(fn, options) { + $(document).bind('iframe:loaded', function(e, data) { + fn(data) + start() + }) + + $('#qunit-fixture').find('a') + .triggerNative('click') +} + +asyncTest('link with "data-method" set to "delete"', 3, function() { + submit(function(data) { + equal(data.REQUEST_METHOD, 'DELETE') + strictEqual(data.params.authenticity_token, undefined) + strictEqual(data.HTTP_X_CSRF_TOKEN, undefined) + }) +}) + +asyncTest('click on the child of link with "data-method"', 3, function() { + $(document).bind('iframe:loaded', function(e, data) { + equal(data.REQUEST_METHOD, 'DELETE') + strictEqual(data.params.authenticity_token, undefined) + strictEqual(data.HTTP_X_CSRF_TOKEN, undefined) + start() + }) + $('#qunit-fixture a').html('<strong>destroy!</strong>').find('strong').triggerNative('click') +}) + +asyncTest('link with "data-method" and CSRF', 1, function() { + $('#qunit-fixture') + .append('<meta name="csrf-param" content="authenticity_token"/>') + .append('<meta name="csrf-token" content="cf50faa3fe97702ca1ae"/>') + + submit(function(data) { + equal(data.params.authenticity_token, 'cf50faa3fe97702ca1ae') + }) +}) + +asyncTest('link "target" should be carried over to generated form', 1, function() { + $('a[data-method]').attr('target', 'super-special-frame') + submit(function(data) { + equal(data.params._target, 'super-special-frame') + }) +}) + +asyncTest('link with "data-method" and cross origin', 1, function() { + var data = {} + + $('#qunit-fixture') + .append('<meta name="csrf-param" content="authenticity_token"/>') + .append('<meta name="csrf-token" content="cf50faa3fe97702ca1ae"/>') + + $(document).on('submit', 'form', function(e) { + $(e.currentTarget).serializeArray().map(function(item) { + data[item.name] = item.value + }) + + return false + }) + + var link = $('#qunit-fixture').find('a') + + link.attr('href', 'http://www.alfajango.com') + + link.triggerNative('click') + + start() + + notEqual(data.authenticity_token, 'cf50faa3fe97702ca1ae') +}) + +})() diff --git a/actionview/test/ujs/public/test/data-remote.js b/actionview/test/ujs/public/test/data-remote.js new file mode 100644 index 0000000000..cbbd4e6c92 --- /dev/null +++ b/actionview/test/ujs/public/test/data-remote.js @@ -0,0 +1,440 @@ +(function() { + +function buildSelect(attrs) { + attrs = $.extend({ + 'name': 'user_data', 'data-remote': 'true', 'data-url': '/echo', 'data-params': 'data1=value1' + }, attrs) + + $('#qunit-fixture').append( + $('<select />', attrs) + .append($('<option />', {value: 'optionValue1', text: 'option1'})) + .append($('<option />', {value: 'optionValue2', text: 'option2'})) + ) +} + +module('data-remote', { + setup: function() { + $('#qunit-fixture') + .append($('<a />', { + href: '/echo', + 'data-remote': 'true', + 'data-params': 'data1=value1&data2=value2', + text: 'my address' + })) + .append($('<button />', { + 'data-url': '/echo', + 'data-remote': 'true', + 'data-params': 'data1=value1&data2=value2', + text: 'my button' + })) + .append($('<form />', { + action: '/echo', + 'data-remote': 'true', + method: 'post', + id: 'my-remote-form' + })) + .append($('<a />', { + href: '/echo', + 'data-remote': 'true', + disabled: 'disabled', + text: 'Disabed link' + })) + .find('form').append($('<input type="text" name="user_name" value="john">')) + + } +}) + +asyncTest('ctrl-clicking on a link does not fire ajaxyness', 0, function() { + var link = $('a[data-remote]') + + // Ideally, we'd setup an iframe to intercept normal link clicks + // and add a test to make sure the iframe:loaded event is triggered. + // However, jquery doesn't actually cause a native `click` event and + // follow links using `trigger('click')`, it only fires bindings. + link + .removeAttr('data-params') + .bindNative('ajax:beforeSend', function() { + ok(false, 'ajax should not be triggered') + }) + + link.triggerNative('click', { metaKey: true }) + link.triggerNative('click', { ctrlKey: true }) + + setTimeout(function() { start() }, 13) +}) + +asyncTest('ctrl-clicking on a link still fires ajax for non-GET links and for links with "data-params"', 2, function() { + var link = $('a[data-remote]') + + link + .removeAttr('data-params') + .attr('data-method', 'POST') + .bindNative('ajax:beforeSend', function() { + ok(true, 'ajax should be triggered') + }) + .triggerNative('click', { metaKey: true }) + + link + .removeAttr('data-method') + .attr('data-params', 'name=steve') + .triggerNative('click', { metaKey: true }) + + setTimeout(function() { start() }, 13) +}) + +asyncTest('clicking on a link with data-remote attribute', 5, function() { + $('a[data-remote]') + .bindNative('ajax:success', function(e, data, status, xhr) { + App.assertCallbackInvoked('ajax:success') + App.assertRequestPath(data, '/echo') + equal(data.params.data1, 'value1', 'ajax arguments should have key data1 with right value') + equal(data.params.data2, 'value2', 'ajax arguments should have key data2 with right value') + App.assertGetRequest(data) + }) + .bindNative('ajax:complete', function() { start() }) + .triggerNative('click') +}) + +asyncTest('clicking on a link with both query string in href and data-params', 4, function() { + $('a[data-remote]') + .attr('href', '/echo?data3=value3') + .bindNative('ajax:success', function(e, data, status, xhr) { + App.assertGetRequest(data) + equal(data.params.data1, 'value1', 'ajax arguments should have key data1 with right value') + equal(data.params.data2, 'value2', 'ajax arguments should have key data2 with right value') + equal(data.params.data3, 'value3', 'query string in url should be passed to server with right value') + }) + .bindNative('ajax:complete', function() { start() }) + .triggerNative('click') +}) + +asyncTest('clicking on a link with both query string in href and data-params with POST method', 4, function() { + $('a[data-remote]') + .attr('href', '/echo?data3=value3') + .attr('data-method', 'post') + .bindNative('ajax:success', function(e, data, status, xhr) { + App.assertPostRequest(data) + equal(data.params.data1, 'value1', 'ajax arguments should have key data1 with right value') + equal(data.params.data2, 'value2', 'ajax arguments should have key data2 with right value') + equal(data.params.data3, 'value3', 'query string in url should be passed to server with right value') + }) + .bindNative('ajax:complete', function() { start() }) + .triggerNative('click') +}) + +asyncTest('clicking on a link with disabled attribute', 0, function() { + $('a[disabled]') + .bindNative('ajax:before', function(e, data, status, xhr) { + App.assertCallbackNotInvoked('ajax:success') + }) + .bindNative('ajax:complete', function() { start() }) + .triggerNative('click') + + setTimeout(function() { + start() + }, 13) +}) + +asyncTest('clicking on a button with data-remote attribute', 5, function() { + $('button[data-remote]') + .bindNative('ajax:success', function(e, data, status, xhr) { + App.assertCallbackInvoked('ajax:success') + App.assertRequestPath(data, '/echo') + equal(data.params.data1, 'value1', 'ajax arguments should have key data1 with right value') + equal(data.params.data2, 'value2', 'ajax arguments should have key data2 with right value') + App.assertGetRequest(data) + }) + .bindNative('ajax:complete', function() { start() }) + .triggerNative('click') +}) + +asyncTest('changing a select option with data-remote attribute', 5, function() { + buildSelect() + + $('select[data-remote]') + .bindNative('ajax:success', function(e, data, status, xhr) { + App.assertCallbackInvoked('ajax:success') + App.assertRequestPath(data, '/echo') + equal(data.params.user_data, 'optionValue2', 'ajax arguments should have key term with right value') + equal(data.params.data1, 'value1', 'ajax arguments should have key data1 with right value') + App.assertGetRequest(data) + }) + .bindNative('ajax:complete', function() { start() }) + .val('optionValue2') + .triggerNative('change') +}) + +asyncTest('submitting form with data-remote attribute', 4, function() { + $('form[data-remote]') + .bindNative('ajax:success', function(e, data, status, xhr) { + App.assertCallbackInvoked('ajax:success') + App.assertRequestPath(data, '/echo') + equal(data.params.user_name, 'john', 'ajax arguments should have key user_name with right value') + App.assertPostRequest(data) + }) + .bindNative('ajax:complete', function() { start() }) + .triggerNative('submit') +}) + +asyncTest('submitting form with data-remote attribute should include inputs in a fieldset only once', 3, function() { + $('form[data-remote]') + .append('<fieldset><input name="items[]" value="Item" /></fieldset>') + .bindNative('ajax:success', function(e, data, status, xhr) { + App.assertCallbackInvoked('ajax:success') + equal(data.params.items.length, 1, 'ajax arguments should only have the item once') + App.assertPostRequest(data) + }) + .bindNative('ajax:complete', function() { + $('form[data-remote], fieldset').remove() + start() + }) + .triggerNative('submit') +}) + +asyncTest('submitting form with data-remote attribute submits input with matching [form] attribute', 6, function() { + $('#qunit-fixture') + .append($('<input type="text" name="user_data" value="value1" form="my-remote-form">')) + .append($('<input type="text" name="user_email" value="from@example.com" disabled="disabled" form="my-remote-form">')) + + $('form[data-remote]') + .bindNative('ajax:success', function(e, data, status, xhr) { + App.assertCallbackInvoked('ajax:success') + App.assertRequestPath(data, '/echo') + equal(data.params.user_name, 'john', 'ajax arguments should have key user_name with right value') + equal(data.params.user_data, 'value1', 'ajax arguments should have key user_data with right value') + equal(data.params.user_email, undefined, 'ajax arguments should not have disabled field') + App.assertPostRequest(data) + }) + .bindNative('ajax:complete', function() { start() }) + .triggerNative('submit') +}) + +asyncTest('submitting form with data-remote attribute by clicking button with matching [form] attribute', 5, function() { + $('form[data-remote]') + .bindNative('ajax:success', function(e, data, status, xhr) { + App.assertCallbackInvoked('ajax:success') + App.assertRequestPath(data, '/echo') + equal(data.params.user_name, 'john', 'ajax arguments should have key user_name with right value') + equal(data.params.user_data, 'value2', 'ajax arguments should have key user_data with right value') + App.assertPostRequest(data) + }) + .bindNative('ajax:complete', function() { start() }) + + $('<button />', { + type: 'submit', + name: 'user_data', + value: 'value1', + form: 'my-remote-form' + }) + .appendTo($('#qunit-fixture')) + + $('<button />', { + type: 'submit', + name: 'user_data', + value: 'value2', + form: 'my-remote-form' + }) + .appendTo($('#qunit-fixture')) + .triggerNative('click') +}) + +asyncTest('form\'s submit bindings in browsers that don\'t support submit bubbling', 5, function() { + var form = $('form[data-remote]'), directBindingCalled = false + + ok(!directBindingCalled, 'nothing is called') + + form + .append($('<input type="submit" />')) + .bindNative('submit', function(event) { + ok(event.type == 'submit', 'submit event handlers are called with submit event') + ok(true, 'binding handler is called') + directBindingCalled = true + }) + .bindNative('ajax:beforeSend', function() { + ok(true, 'form being submitted via ajax') + ok(directBindingCalled, 'binding handler already called') + }) + .bindNative('ajax:complete', function() { + start() + }) + + if(!$.support.submitBubbles) { + // Must indrectly submit form via click to trigger jQuery's manual submit bubbling in IE + form.find('input[type=submit]') + .triggerNative('click') + } else { + form.triggerNative('submit') + } +}) + +asyncTest('returning false in form\'s submit bindings in non-submit-bubbling browsers', 1, function() { + var form = $('form[data-remote]') + + form + .append($('<input type="submit" />')) + .bindNative('submit', function() { + ok(true, 'binding handler is called') + return false + }) + .bindNative('ajax:beforeSend', function() { + ok(false, 'form should not be submitted') + }) + + if (!$.support.submitBubbles) { + // Must indrectly submit form via click to trigger jQuery's manual submit bubbling in IE + form.find('input[type=submit]').triggerNative('click') + } else { + form.triggerNative('submit') + } + + setTimeout(function() { start() }, 13) +}) + +asyncTest('clicking on a link with falsy "data-remote" attribute does not fire ajaxyness', 0, function() { + $('a[data-remote]') + .attr('data-remote', 'false') + .bindNative('ajax:beforeSend', function() { + ok(false, 'ajax should not be triggered') + }) + .bindNative('click', function() { + return false + }) + .triggerNative('click') + + setTimeout(function() { start() }, 20) +}) + +asyncTest('ctrl-clicking on a link with falsy "data-remote" attribute does not fire ajaxyness even if "data-params" present', 0, function() { + var link = $('a[data-remote]') + + link + .removeAttr('data-params') + .attr('data-remote', 'false') + .attr('data-method', 'POST') + .bindNative('ajax:beforeSend', function() { + ok(false, 'ajax should not be triggered') + }) + .bindNative('click', function() { + return false + }) + .triggerNative('click', { metaKey: true }) + + link + .removeAttr('data-method') + .attr('data-params', 'name=steve') + .triggerNative('click', { metaKey: true }) + + setTimeout(function() { start() }, 20) +}) + +asyncTest('clicking on a button with falsy "data-remote" attribute', 0, function() { + $('button[data-remote]:first') + .attr('data-remote', 'false') + .bindNative('ajax:beforeSend', function() { + ok(false, 'ajax should not be triggered') + }) + .bindNative('click', function() { + return false + }) + .triggerNative('click') + + setTimeout(function() { start() }, 20) +}) + +asyncTest('submitting a form with falsy "data-remote" attribute', 0, function() { + $('form[data-remote]:first') + .attr('data-remote', 'false') + .bindNative('ajax:beforeSend', function() { + ok(false, 'ajax should not be triggered') + }) + .bindNative('submit', function() { + return false + }) + .triggerNative('submit') + + setTimeout(function() { start() }, 20) +}) + +asyncTest('changing a select option with falsy "data-remote" attribute', 0, function() { + buildSelect({'data-remote': 'false'}) + + $('select[data-remote=false]:first') + .bindNative('ajax:beforeSend', function() { + ok(false, 'ajax should not be triggered') + }) + .val('optionValue2') + .triggerNative('change') + + setTimeout(function() { start() }, 20) +}) + +asyncTest('form should be serialized correctly', 6, function() { + $('form') + .append('<textarea name="textarea">textarea</textarea>') + .append('<input type="checkbox" name="checkbox[]" value="0" />') + .append('<input type="checkbox" checked="checked" name="checkbox[]" value="1" />') + .append('<input type="radio" checked="checked" name="radio" value="0" />') + .append('<input type="radio" name="radio" value="1" />') + .append('<select multiple="multiple" name="select[]">\ + <option value="1" selected>1</option>\ + <option value="2" selected>2</option>\ + <option value="3">3</option>\ + <option selected>4</option>\ + </select>') + .bindNative('ajax:success', function(e, data, status, xhr) { + equal(data.params.checkbox.length, 1) + equal(data.params.checkbox[0], '1') + equal(data.params.radio, '0') + equal(data.params.select.length, 3) + equal(data.params.select[2], '4') + equal(data.params.textarea, 'textarea') + + start() + }) + .triggerNative('submit') +}) + +asyncTest('form buttons should only be serialized when clicked', 4, function() { + $('form') + .append('<input type="submit" name="submit1" value="submit1" />') + .append('<button name="submit2" value="submit2" />') + .append('<button name="submit3" value="submit3" />') + .bindNative('ajax:success', function(e, data, status, xhr) { + equal(data.params.submit1, undefined) + equal(data.params.submit2, 'submit2') + equal(data.params.submit3, undefined) + equal(data['rack.request.form_vars'], 'user_name=john&submit2=submit2') + + start() + }) + .find('[name=submit2]').triggerNative('click') +}) + +asyncTest('changing a select option without "data-url" attribute still fires ajax request to current location', 1, function() { + var currentLocation, ajaxLocation + + buildSelect({'data-url': ''}) + + $('select[data-remote]') + .bindNative('ajax:beforeSend', function(e, xhr, settings) { + // Get current location (the same way jQuery does) + try { + currentLocation = location.href + } catch(err) { + currentLocation = document.createElement( 'a' ) + currentLocation.href = '' + currentLocation = currentLocation.href + } + + ajaxLocation = settings.url.replace(settings.data, '').replace(/&$/, '').replace(/\?$/, '') + equal(ajaxLocation, currentLocation, 'URL should be current page by default') + + return false + }) + .val('optionValue2') + .triggerNative('change') + + setTimeout(function() { start() }, 20) +}) + +})() diff --git a/actionview/test/ujs/public/test/override.js b/actionview/test/ujs/public/test/override.js new file mode 100644 index 0000000000..299c7018cc --- /dev/null +++ b/actionview/test/ujs/public/test/override.js @@ -0,0 +1,56 @@ +(function() { + +var realHref + +module('override', { + setup: function() { + realHref = $.rails.href + $('#qunit-fixture') + .append($('<a />', { + href: '/real/href', 'data-remote': 'true', 'data-method': 'delete', 'data-href': '/data/href' + })) + }, + teardown: function() { + $.rails.href = realHref + } +}) + +asyncTest('the getter for an element\'s href is publicly accessible', 1, function() { + ok($.rails.href) + start() +}) + +asyncTest('the getter for an element\'s href is overridable', 1, function() { + $.rails.href = function(element) { return $(element).data('href') } + $('#qunit-fixture a') + .bindNative('ajax:beforeSend', function(e, xhr, options) { + equal('/data/href', options.url) + return false + }) + .triggerNative('click') + start() +}) + +asyncTest('the getter for an element\'s href works normally if not overridden', 1, function() { + $('#qunit-fixture a') + .bindNative('ajax:beforeSend', function(e, xhr, options) { + equal(location.protocol + '//' + location.host + '/real/href', options.url) + return false + }) + .triggerNative('click') + start() +}) + +asyncTest('the event selector strings are overridable', 1, function() { + ok($.rails.linkClickSelector.indexOf(', a[data-custom-remote-link]') != -1, 'linkClickSelector contains custom selector') + start() +}) + +asyncTest('including rails-ujs multiple times throws error', 1, function() { + throws(function() { + Rails.start() + }, 'appending rails.js again throws error') + setTimeout(function() { start() }, 50) +}) + +})() diff --git a/actionview/test/ujs/public/test/settings.js b/actionview/test/ujs/public/test/settings.js new file mode 100644 index 0000000000..299c71bb00 --- /dev/null +++ b/actionview/test/ujs/public/test/settings.js @@ -0,0 +1,116 @@ +var App = App || {} + +App.assertCallbackInvoked = function(callbackName) { + ok(true, callbackName + ' callback should have been invoked') +} + +App.assertCallbackNotInvoked = function(callbackName) { + ok(false, callbackName + ' callback should not have been invoked') +} + +App.assertGetRequest = function(requestEnv) { + equal(requestEnv['REQUEST_METHOD'], 'GET', 'request type should be GET') +} + +App.assertPostRequest = function(requestEnv) { + equal(requestEnv['REQUEST_METHOD'], 'POST', 'request type should be POST') +} + +App.assertRequestPath = function(requestEnv, path) { + equal(requestEnv['PATH_INFO'], path, 'request should be sent to right url') +} + +App.getVal = function(el) { + return el.is('input,textarea,select') ? el.val() : el.text() +} + +App.disabled = function(el) { + return el.is('input,textarea,select,button') ? + (el.is(':disabled') && $.rails.getData(el[0], 'ujs:disabled')) : + $.rails.getData(el[0], 'ujs:disabled') +} + +App.checkEnabledState = function(el, text) { + ok(!App.disabled(el), el.get(0).tagName + ' should not be disabled') + equal(App.getVal(el), text, el.get(0).tagName + ' text should be original value') +} + +App.checkDisabledState = function(el, text) { + ok(App.disabled(el), el.get(0).tagName + ' should be disabled') + equal(App.getVal(el), text, el.get(0).tagName + ' text should be disabled value') +} + +// hijacks normal form submit; lets it submit to an iframe to prevent +// navigating away from the test suite +$(document).bind('submit', function(e) { + if (!e.isDefaultPrevented()) { + var form = $(e.target), action = form.attr('action'), + name = 'form-frame' + jQuery.guid++, + iframe = $('<iframe name="' + name + '" />'), + iframeInput = '<input name="iframe" value="true" type="hidden" />' + targetInput = '<input name="_target" value="' + (form.attr('target') || '') + '" type="hidden" />' + + if (action && action.indexOf('iframe') < 0) { + if (action.indexOf('?') < 0) { + form.attr('action', action + '?iframe=true') + } else { + form.attr('action', action + '&iframe=true') + } + } + form.attr('target', name).append(iframeInput, targetInput) + $('#qunit-fixture').append(iframe) + $.event.trigger('iframe:loading', form) + } +}) + +var _MouseEvent = window.MouseEvent + +try { + new _MouseEvent() +} catch (e) { + _MouseEvent = function(type, options) { + var evt = document.createEvent('MouseEvents') + evt.initMouseEvent(type, options.bubbles, options.cancelable, window, options.detail, 0, 0, 80, 20, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, 0, null) + return evt + } +} + +$.fn.extend({ + // trigger a native click event + triggerNative: function(type, options) { + var el = this[0], + event, + Evt = { + 'click': _MouseEvent, + 'change': Event, + 'pageshow': PageTransitionEvent, + 'submit': Event + }[type] + + options = options || {} + options.bubbles = true + options.cancelable = true + + event = new Evt(type, options) + + el.dispatchEvent(event) + + if (type === 'submit' && !event.defaultPrevented) { + el.submit() + } + return this + }, + bindNative: function(event, handler) { + if (!handler) return this + + this.bind(event, function(e) { + var args = [] + if (e.originalEvent.detail) { + args = e.originalEvent.detail.slice() + } + args.unshift(e) + return handler.apply(this, args) + }) + return this + } +}) diff --git a/actionview/test/ujs/public/vendor/jquery-2.2.0.js b/actionview/test/ujs/public/vendor/jquery-2.2.0.js new file mode 100644 index 0000000000..1e0ba99740 --- /dev/null +++ b/actionview/test/ujs/public/vendor/jquery-2.2.0.js @@ -0,0 +1,9831 @@ +/*! + * jQuery JavaScript Library v2.2.0 + * http://jquery.com/ + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * + * Copyright jQuery Foundation and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2016-01-08T20:02Z + */ + +(function( global, factory ) { + + if ( typeof module === "object" && typeof module.exports === "object" ) { + // For CommonJS and CommonJS-like environments where a proper `window` + // is present, execute the factory and get jQuery. + // For environments that do not have a `window` with a `document` + // (such as Node.js), expose a factory as module.exports. + // This accentuates the need for the creation of a real `window`. + // e.g. var jQuery = require("jquery")(window); + // See ticket #14549 for more info. + module.exports = global.document ? + factory( global, true ) : + function( w ) { + if ( !w.document ) { + throw new Error( "jQuery requires a window with a document" ); + } + return factory( w ); + }; + } else { + factory( global ); + } + +// Pass this if window is not defined yet +}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { + +// Support: Firefox 18+ +// Can't be in strict mode, several libs including ASP.NET trace +// the stack via arguments.caller.callee and Firefox dies if +// you try to trace through "use strict" call chains. (#13335) +//"use strict"; +var arr = []; + +var document = window.document; + +var slice = arr.slice; + +var concat = arr.concat; + +var push = arr.push; + +var indexOf = arr.indexOf; + +var class2type = {}; + +var toString = class2type.toString; + +var hasOwn = class2type.hasOwnProperty; + +var support = {}; + + + +var + version = "2.2.0", + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + + // The jQuery object is actually just the init constructor 'enhanced' + // Need init if jQuery is called (just allow error to be thrown if not included) + return new jQuery.fn.init( selector, context ); + }, + + // Support: Android<4.1 + // Make sure we trim BOM and NBSP + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, + + // Matches dashed string for camelizing + rmsPrefix = /^-ms-/, + rdashAlpha = /-([\da-z])/gi, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return letter.toUpperCase(); + }; + +jQuery.fn = jQuery.prototype = { + + // The current version of jQuery being used + jquery: version, + + constructor: jQuery, + + // Start with an empty selector + selector: "", + + // The default length of a jQuery object is 0 + length: 0, + + toArray: function() { + return slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num != null ? + + // Return just the one element from the set + ( num < 0 ? this[ num + this.length ] : this[ num ] ) : + + // Return all the elements in a clean array + slice.call( this ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + ret.context = this.context; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + each: function( callback ) { + return jQuery.each( this, callback ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map( this, function( elem, i ) { + return callback.call( elem, i, elem ); + } ) ); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ) ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); + }, + + end: function() { + return this.prevObject || this.constructor(); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: arr.sort, + splice: arr.splice +}; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[ 0 ] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + + // Skip the boolean and the target + target = arguments[ i ] || {}; + i++; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction( target ) ) { + target = {}; + } + + // Extend jQuery itself if only one argument is passed + if ( i === length ) { + target = this; + i--; + } + + for ( ; i < length; i++ ) { + + // Only deal with non-null/undefined values + if ( ( options = arguments[ i ] ) != null ) { + + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject( copy ) || + ( copyIsArray = jQuery.isArray( copy ) ) ) ) { + + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray( src ) ? src : []; + + } else { + clone = src && jQuery.isPlainObject( src ) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend( { + + // Unique for each copy of jQuery on the page + expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), + + // Assume jQuery is ready without the ready module + isReady: true, + + error: function( msg ) { + throw new Error( msg ); + }, + + noop: function() {}, + + isFunction: function( obj ) { + return jQuery.type( obj ) === "function"; + }, + + isArray: Array.isArray, + + isWindow: function( obj ) { + return obj != null && obj === obj.window; + }, + + isNumeric: function( obj ) { + + // parseFloat NaNs numeric-cast false positives (null|true|false|"") + // ...but misinterprets leading-number strings, particularly hex literals ("0x...") + // subtraction forces infinities to NaN + // adding 1 corrects loss of precision from parseFloat (#15100) + var realStringObj = obj && obj.toString(); + return !jQuery.isArray( obj ) && ( realStringObj - parseFloat( realStringObj ) + 1 ) >= 0; + }, + + isPlainObject: function( obj ) { + + // Not plain objects: + // - Any object or value whose internal [[Class]] property is not "[object Object]" + // - DOM nodes + // - window + if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + if ( obj.constructor && + !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { + return false; + } + + // If the function hasn't returned already, we're confident that + // |obj| is a plain object, created by {} or constructed with new Object + return true; + }, + + isEmptyObject: function( obj ) { + var name; + for ( name in obj ) { + return false; + } + return true; + }, + + type: function( obj ) { + if ( obj == null ) { + return obj + ""; + } + + // Support: Android<4.0, iOS<6 (functionish RegExp) + return typeof obj === "object" || typeof obj === "function" ? + class2type[ toString.call( obj ) ] || "object" : + typeof obj; + }, + + // Evaluates a script in a global context + globalEval: function( code ) { + var script, + indirect = eval; + + code = jQuery.trim( code ); + + if ( code ) { + + // If the code includes a valid, prologue position + // strict mode pragma, execute code by injecting a + // script tag into the document. + if ( code.indexOf( "use strict" ) === 1 ) { + script = document.createElement( "script" ); + script.text = code; + document.head.appendChild( script ).parentNode.removeChild( script ); + } else { + + // Otherwise, avoid the DOM node creation, insertion + // and removal by using an indirect global eval + + indirect( code ); + } + } + }, + + // Convert dashed to camelCase; used by the css and data modules + // Support: IE9-11+ + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + }, + + each: function( obj, callback ) { + var length, i = 0; + + if ( isArrayLike( obj ) ) { + length = obj.length; + for ( ; i < length; i++ ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } else { + for ( i in obj ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } + + return obj; + }, + + // Support: Android<4.1 + trim: function( text ) { + return text == null ? + "" : + ( text + "" ).replace( rtrim, "" ); + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArrayLike( Object( arr ) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + return arr == null ? -1 : indexOf.call( arr, elem, i ); + }, + + merge: function( first, second ) { + var len = +second.length, + j = 0, + i = first.length; + + for ( ; j < len; j++ ) { + first[ i++ ] = second[ j ]; + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, invert ) { + var callbackInverse, + matches = [], + i = 0, + length = elems.length, + callbackExpect = !invert; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + callbackInverse = !callback( elems[ i ], i ); + if ( callbackInverse !== callbackExpect ) { + matches.push( elems[ i ] ); + } + } + + return matches; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var length, value, + i = 0, + ret = []; + + // Go through the array, translating each of the items to their new values + if ( isArrayLike( elems ) ) { + length = elems.length; + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + } + + // Flatten any nested arrays + return concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + var tmp, args, proxy; + + if ( typeof context === "string" ) { + tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + args = slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || jQuery.guid++; + + return proxy; + }, + + now: Date.now, + + // jQuery.support is not used in Core but other projects attach their + // properties to it so it needs to exist. + support: support +} ); + +// JSHint would error on this code due to the Symbol not being defined in ES5. +// Defining this global in .jshintrc would create a danger of using the global +// unguarded in another place, it seems safer to just disable JSHint for these +// three lines. +/* jshint ignore: start */ +if ( typeof Symbol === "function" ) { + jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; +} +/* jshint ignore: end */ + +// Populate the class2type map +jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), +function( i, name ) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +} ); + +function isArrayLike( obj ) { + + // Support: iOS 8.2 (not reproducible in simulator) + // `in` check used to prevent JIT error (gh-2145) + // hasOwn isn't used here due to false negatives + // regarding Nodelist length in IE + var length = !!obj && "length" in obj && obj.length, + type = jQuery.type( obj ); + + if ( type === "function" || jQuery.isWindow( obj ) ) { + return false; + } + + return type === "array" || length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj; +} +var Sizzle = +/*! + * Sizzle CSS Selector Engine v2.2.1 + * http://sizzlejs.com/ + * + * Copyright jQuery Foundation and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2015-10-17 + */ +(function( window ) { + +var i, + support, + Expr, + getText, + isXML, + tokenize, + compile, + select, + outermostContext, + sortInput, + hasDuplicate, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + 1 * new Date(), + preferredDoc = window.document, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + } + return 0; + }, + + // General-purpose constants + MAX_NEGATIVE = 1 << 31, + + // Instance methods + hasOwn = ({}).hasOwnProperty, + arr = [], + pop = arr.pop, + push_native = arr.push, + push = arr.push, + slice = arr.slice, + // Use a stripped-down indexOf as it's faster than native + // http://jsperf.com/thor-indexof-vs-for/5 + indexOf = function( list, elem ) { + var i = 0, + len = list.length; + for ( ; i < len; i++ ) { + if ( list[i] === elem ) { + return i; + } + } + return -1; + }, + + booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", + + // Regular expressions + + // http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + + // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", + + // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + + // Operator (capture 2) + "*([*^$|!~]?=)" + whitespace + + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + + "*\\]", + + pseudos = ":(" + identifier + ")(?:\\((" + + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: + // 1. quoted (capture 3; capture 4 or capture 5) + "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + + // 2. simple (capture 6) + "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + + // 3. anything else (capture 2) + ".*" + + ")\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rwhitespace = new RegExp( whitespace + "+", "g" ), + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), + + rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), + + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + identifier + ")" ), + "CLASS": new RegExp( "^\\.(" + identifier + ")" ), + "TAG": new RegExp( "^(" + identifier + "|[*])" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rnative = /^[^{]+\{\s*\[native \w/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rsibling = /[+~]/, + rescape = /'|\\/g, + + // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), + funescape = function( _, escaped, escapedWhitespace ) { + var high = "0x" + escaped - 0x10000; + // NaN means non-codepoint + // Support: Firefox<24 + // Workaround erroneous numeric interpretation of +"0x" + return high !== high || escapedWhitespace ? + escaped : + high < 0 ? + // BMP codepoint + String.fromCharCode( high + 0x10000 ) : + // Supplemental Plane codepoint (surrogate pair) + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }, + + // Used for iframes + // See setDocument() + // Removing the function wrapper causes a "Permission Denied" + // error in IE + unloadHandler = function() { + setDocument(); + }; + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + (arr = slice.call( preferredDoc.childNodes )), + preferredDoc.childNodes + ); + // Support: Android<4.0 + // Detect silently failing push.apply + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + push_native.apply( target, slice.call(els) ); + } : + + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + // Can't trust NodeList.length + while ( (target[j++] = els[i++]) ) {} + target.length = j - 1; + } + }; +} + +function Sizzle( selector, context, results, seed ) { + var m, i, elem, nid, nidselect, match, groups, newSelector, + newContext = context && context.ownerDocument, + + // nodeType defaults to 9, since context defaults to document + nodeType = context ? context.nodeType : 9; + + results = results || []; + + // Return early from calls with invalid selector or context + if ( typeof selector !== "string" || !selector || + nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { + + return results; + } + + // Try to shortcut find operations (as opposed to filters) in HTML documents + if ( !seed ) { + + if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { + setDocument( context ); + } + context = context || document; + + if ( documentIsHTML ) { + + // If the selector is sufficiently simple, try using a "get*By*" DOM method + // (excepting DocumentFragment context, where the methods don't exist) + if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { + + // ID selector + if ( (m = match[1]) ) { + + // Document context + if ( nodeType === 9 ) { + if ( (elem = context.getElementById( m )) ) { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + + // Element context + } else { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( newContext && (elem = newContext.getElementById( m )) && + contains( context, elem ) && + elem.id === m ) { + + results.push( elem ); + return results; + } + } + + // Type selector + } else if ( match[2] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Class selector + } else if ( (m = match[3]) && support.getElementsByClassName && + context.getElementsByClassName ) { + + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // Take advantage of querySelectorAll + if ( support.qsa && + !compilerCache[ selector + " " ] && + (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { + + if ( nodeType !== 1 ) { + newContext = context; + newSelector = selector; + + // qSA looks outside Element context, which is not what we want + // Thanks to Andrew Dupont for this workaround technique + // Support: IE <=8 + // Exclude object elements + } else if ( context.nodeName.toLowerCase() !== "object" ) { + + // Capture the context ID, setting it first if necessary + if ( (nid = context.getAttribute( "id" )) ) { + nid = nid.replace( rescape, "\\$&" ); + } else { + context.setAttribute( "id", (nid = expando) ); + } + + // Prefix every selector in the list + groups = tokenize( selector ); + i = groups.length; + nidselect = ridentifier.test( nid ) ? "#" + nid : "[id='" + nid + "']"; + while ( i-- ) { + groups[i] = nidselect + " " + toSelector( groups[i] ); + } + newSelector = groups.join( "," ); + + // Expand context for sibling selectors + newContext = rsibling.test( selector ) && testContext( context.parentNode ) || + context; + } + + if ( newSelector ) { + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch ( qsaError ) { + } finally { + if ( nid === expando ) { + context.removeAttribute( "id" ); + } + } + } + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); +} + +/** + * Create key-value caches of limited size + * @returns {function(string, object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var keys = []; + + function cache( key, value ) { + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key + " " ) > Expr.cacheLength ) { + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return (cache[ key + " " ] = value); + } + return cache; +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created div and expects a boolean result + */ +function assert( fn ) { + var div = document.createElement("div"); + + try { + return !!fn( div ); + } catch (e) { + return false; + } finally { + // Remove from its parent by default + if ( div.parentNode ) { + div.parentNode.removeChild( div ); + } + // release memory in IE + div = null; + } +} + +/** + * Adds the same handler for all of the specified attrs + * @param {String} attrs Pipe-separated list of attributes + * @param {Function} handler The method that will be applied + */ +function addHandle( attrs, handler ) { + var arr = attrs.split("|"), + i = arr.length; + + while ( i-- ) { + Expr.attrHandle[ arr[i] ] = handler; + } +} + +/** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b + */ +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && a.nodeType === 1 && b.nodeType === 1 && + ( ~b.sourceIndex || MAX_NEGATIVE ) - + ( ~a.sourceIndex || MAX_NEGATIVE ); + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( (cur = cur.nextSibling) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +/** + * Returns a function to use in pseudos for input types + * @param {String} type + */ +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for buttons + * @param {String} type + */ +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for positionals + * @param {Function} fn + */ +function createPositionalPseudo( fn ) { + return markFunction(function( argument ) { + argument = +argument; + return markFunction(function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ (j = matchIndexes[i]) ] ) { + seed[j] = !(matches[j] = seed[j]); + } + } + }); + }); +} + +/** + * Checks a node for validity as a Sizzle context + * @param {Element|Object=} context + * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value + */ +function testContext( context ) { + return context && typeof context.getElementsByTagName !== "undefined" && context; +} + +// Expose support vars for convenience +support = Sizzle.support = {}; + +/** + * Detects XML nodes + * @param {Element|Object} elem An element or a document + * @returns {Boolean} True iff elem is a non-HTML XML node + */ +isXML = Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = elem && (elem.ownerDocument || elem).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +/** + * Sets document-related variables once based on the current document + * @param {Element|Object} [doc] An element or document object to use to set the document + * @returns {Object} Returns the current document + */ +setDocument = Sizzle.setDocument = function( node ) { + var hasCompare, parent, + doc = node ? node.ownerDocument || node : preferredDoc; + + // Return early if doc is invalid or already selected + if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { + return document; + } + + // Update global variables + document = doc; + docElem = document.documentElement; + documentIsHTML = !isXML( document ); + + // Support: IE 9-11, Edge + // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) + if ( (parent = document.defaultView) && parent.top !== parent ) { + // Support: IE 11 + if ( parent.addEventListener ) { + parent.addEventListener( "unload", unloadHandler, false ); + + // Support: IE 9 - 10 only + } else if ( parent.attachEvent ) { + parent.attachEvent( "onunload", unloadHandler ); + } + } + + /* Attributes + ---------------------------------------------------------------------- */ + + // Support: IE<8 + // Verify that getAttribute really returns attributes and not properties + // (excepting IE8 booleans) + support.attributes = assert(function( div ) { + div.className = "i"; + return !div.getAttribute("className"); + }); + + /* getElement(s)By* + ---------------------------------------------------------------------- */ + + // Check if getElementsByTagName("*") returns only elements + support.getElementsByTagName = assert(function( div ) { + div.appendChild( document.createComment("") ); + return !div.getElementsByTagName("*").length; + }); + + // Support: IE<9 + support.getElementsByClassName = rnative.test( document.getElementsByClassName ); + + // Support: IE<10 + // Check if getElementById returns elements by name + // The broken getElementById methods don't pick up programatically-set names, + // so use a roundabout getElementsByName test + support.getById = assert(function( div ) { + docElem.appendChild( div ).id = expando; + return !document.getElementsByName || !document.getElementsByName( expando ).length; + }); + + // ID find and filter + if ( support.getById ) { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var m = context.getElementById( id ); + return m ? [ m ] : []; + } + }; + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute("id") === attrId; + }; + }; + } else { + // Support: IE6/7 + // getElementById is not reliable as a find shortcut + delete Expr.find["ID"]; + + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== "undefined" && + elem.getAttributeNode("id"); + return node && node.value === attrId; + }; + }; + } + + // Tag + Expr.find["TAG"] = support.getElementsByTagName ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( tag ); + + // DocumentFragment nodes don't have gEBTN + } else if ( support.qsa ) { + return context.querySelectorAll( tag ); + } + } : + + function( tag, context ) { + var elem, + tmp = [], + i = 0, + // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too + results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + while ( (elem = results[i++]) ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }; + + // Class + Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { + if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { + return context.getElementsByClassName( className ); + } + }; + + /* QSA/matchesSelector + ---------------------------------------------------------------------- */ + + // QSA and matchesSelector support + + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + rbuggyMatches = []; + + // qSa(:focus) reports false when true (Chrome 21) + // We allow this because of a bug in IE8/9 that throws an error + // whenever `document.activeElement` is accessed on an iframe + // So, we allow :focus to pass through QSA all the time to avoid the IE error + // See http://bugs.jquery.com/ticket/13378 + rbuggyQSA = []; + + if ( (support.qsa = rnative.test( document.querySelectorAll )) ) { + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert(function( div ) { + // Select is set to empty string on purpose + // This is to test IE's treatment of not explicitly + // setting a boolean content attribute, + // since its presence should be enough + // http://bugs.jquery.com/ticket/12359 + docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" + + "<select id='" + expando + "-\r\\' msallowcapture=''>" + + "<option selected=''></option></select>"; + + // Support: IE8, Opera 11-12.16 + // Nothing should be selected when empty strings follow ^= or $= or *= + // The test attribute must be unknown in Opera but "safe" for WinRT + // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section + if ( div.querySelectorAll("[msallowcapture^='']").length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); + } + + // Support: IE8 + // Boolean attributes and "value" are not treated correctly + if ( !div.querySelectorAll("[selected]").length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); + } + + // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ + if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) { + rbuggyQSA.push("~="); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":checked").length ) { + rbuggyQSA.push(":checked"); + } + + // Support: Safari 8+, iOS 8+ + // https://bugs.webkit.org/show_bug.cgi?id=136851 + // In-page `selector#id sibing-combinator selector` fails + if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) { + rbuggyQSA.push(".#.+[+~]"); + } + }); + + assert(function( div ) { + // Support: Windows 8 Native Apps + // The type and name attributes are restricted during .innerHTML assignment + var input = document.createElement("input"); + input.setAttribute( "type", "hidden" ); + div.appendChild( input ).setAttribute( "name", "D" ); + + // Support: IE8 + // Enforce case-sensitivity of name attribute + if ( div.querySelectorAll("[name=d]").length ) { + rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":enabled").length ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Opera 10-11 does not throw on post-comma invalid pseudos + div.querySelectorAll("*,:x"); + rbuggyQSA.push(",.*:"); + }); + } + + if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || + docElem.webkitMatchesSelector || + docElem.mozMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector) )) ) { + + assert(function( div ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + support.disconnectedMatch = matches.call( div, "div" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( div, "[s!='']:x" ); + rbuggyMatches.push( "!=", pseudos ); + }); + } + + rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); + rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); + + /* Contains + ---------------------------------------------------------------------- */ + hasCompare = rnative.test( docElem.compareDocumentPosition ); + + // Element contains another + // Purposefully self-exclusive + // As in, an element does not contain itself + contains = hasCompare || rnative.test( docElem.contains ) ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && ( + adown.contains ? + adown.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + )); + } : + function( a, b ) { + if ( b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + } + return false; + }; + + /* Sorting + ---------------------------------------------------------------------- */ + + // Document order sorting + sortOrder = hasCompare ? + function( a, b ) { + + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + // Sort on method existence if only one input has compareDocumentPosition + var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; + if ( compare ) { + return compare; + } + + // Calculate position if both inputs belong to the same document + compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? + a.compareDocumentPosition( b ) : + + // Otherwise we know they are disconnected + 1; + + // Disconnected nodes + if ( compare & 1 || + (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { + + // Choose the first element that is related to our preferred document + if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { + return -1; + } + if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { + return 1; + } + + // Maintain original order + return sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + } + + return compare & 4 ? -1 : 1; + } : + function( a, b ) { + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // Parentless nodes are either documents or disconnected + if ( !aup || !bup ) { + return a === document ? -1 : + b === document ? 1 : + aup ? -1 : + bup ? 1 : + sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } + + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( (cur = cur.parentNode) ) { + ap.unshift( cur ); + } + cur = b; + while ( (cur = cur.parentNode) ) { + bp.unshift( cur ); + } + + // Walk down the tree looking for a discrepancy + while ( ap[i] === bp[i] ) { + i++; + } + + return i ? + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[i], bp[i] ) : + + // Otherwise nodes in our document sort first + ap[i] === preferredDoc ? -1 : + bp[i] === preferredDoc ? 1 : + 0; + }; + + return document; +}; + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + // Make sure that attribute selectors are quoted + expr = expr.replace( rattributeQuotes, "='$1']" ); + + if ( support.matchesSelector && documentIsHTML && + !compilerCache[ expr + " " ] && + ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && + ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { + + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || support.disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch (e) {} + } + + return Sizzle( expr, document, null, [ elem ] ).length > 0; +}; + +Sizzle.contains = function( context, elem ) { + // Set document vars if needed + if ( ( context.ownerDocument || context ) !== document ) { + setDocument( context ); + } + return contains( context, elem ); +}; + +Sizzle.attr = function( elem, name ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + var fn = Expr.attrHandle[ name.toLowerCase() ], + // Don't get fooled by Object.prototype properties (jQuery #13807) + val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? + fn( elem, name, !documentIsHTML ) : + undefined; + + return val !== undefined ? + val : + support.attributes || !documentIsHTML ? + elem.getAttribute( name ) : + (val = elem.getAttributeNode(name)) && val.specified ? + val.value : + null; +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +/** + * Document sorting and removing duplicates + * @param {ArrayLike} results + */ +Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + j = 0, + i = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + sortInput = !support.sortStable && results.slice( 0 ); + results.sort( sortOrder ); + + if ( hasDuplicate ) { + while ( (elem = results[i++]) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + // Clear input after sorting to release objects + // See https://github.com/jquery/sizzle/pull/225 + sortInput = null; + + return results; +}; + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + // If no nodeType, this is expected to be an array + while ( (node = elem[i++]) ) { + // Do not traverse comment nodes + ret += getText( node ); + } + } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent for elements + // innerText usage removed for consistency of new lines (jQuery #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + // Do not include comment or processing instruction nodes + + return ret; +}; + +Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + attrHandle: {}, + + find: {}, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[1] = match[1].replace( runescape, funescape ); + + // Move the given value to match[3] whether quoted or unquoted + match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); + + if ( match[2] === "~=" ) { + match[3] = " " + match[3] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[1] = match[1].toLowerCase(); + + if ( match[1].slice( 0, 3 ) === "nth" ) { + // nth-* requires argument + if ( !match[3] ) { + Sizzle.error( match[0] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); + match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); + + // other types prohibit arguments + } else if ( match[3] ) { + Sizzle.error( match[0] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var excess, + unquoted = !match[6] && match[2]; + + if ( matchExpr["CHILD"].test( match[0] ) ) { + return null; + } + + // Accept quoted arguments as-is + if ( match[3] ) { + match[2] = match[4] || match[5] || ""; + + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + // Get excess from tokenize (recursively) + (excess = tokenize( unquoted, true )) && + // advance to the next closing parenthesis + (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { + + // excess is a negative index + match[0] = match[0].slice( 0, excess ); + match[2] = unquoted.slice( 0, excess ); + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + + "TAG": function( nodeNameSelector ) { + var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); + return nodeNameSelector === "*" ? + function() { return true; } : + function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ className + " " ]; + + return pattern || + (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && + classCache( className, function( elem ) { + return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); + }); + }, + + "ATTR": function( name, operator, check ) { + return function( elem ) { + var result = Sizzle.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.slice( -check.length ) === check : + operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + }; + }, + + "CHILD": function( type, what, argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, context, xml ) { + var cache, uniqueCache, outerCache, node, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType, + diff = false; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( (node = node[ dir ]) ) { + if ( ofType ? + node.nodeName.toLowerCase() === name : + node.nodeType === 1 ) { + + return false; + } + } + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + + // Seek `elem` from a previously-cached index + + // ...in a gzip-friendly way + node = parent; + outerCache = node[ expando ] || (node[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + (outerCache[ node.uniqueID ] = {}); + + cache = uniqueCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex && cache[ 2 ]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( (node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + (diff = nodeIndex = 0) || start.pop()) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + } else { + // Use previously-cached element index if available + if ( useCache ) { + // ...in a gzip-friendly way + node = elem; + outerCache = node[ expando ] || (node[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + (outerCache[ node.uniqueID ] = {}); + + cache = uniqueCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex; + } + + // xml :nth-child(...) + // or :nth-last-child(...) or :nth(-last)?-of-type(...) + if ( diff === false ) { + // Use the same loop as above to seek `elem` from the start + while ( (node = ++nodeIndex && node && node[ dir ] || + (diff = nodeIndex = 0) || start.pop()) ) { + + if ( ( ofType ? + node.nodeName.toLowerCase() === name : + node.nodeType === 1 ) && + ++diff ) { + + // Cache the index of each encountered element + if ( useCache ) { + outerCache = node[ expando ] || (node[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + (outerCache[ node.uniqueID ] = {}); + + uniqueCache[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + // Potentially complex pseudos + "not": markFunction(function( selector ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + // Don't keep the element (issue #299) + input[0] = null; + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), + + "contains": markFunction(function( text ) { + text = text.replace( runescape, funescape ); + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + // lang value must be a valid identifier + if ( !ridentifier.test(lang || "") ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( (elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); + return false; + }; + }), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + // Boolean properties + "enabled": function( elem ) { + return elem.disabled === false; + }, + + "disabled": function( elem ) { + return elem.disabled === true; + }, + + "checked": function( elem ) { + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); + }, + + "selected": function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), + // but not by others (comment: 8; processing instruction: 7; etc.) + // nodeType < 6 works because attributes (2) do not appear as children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeType < 6 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + + // Support: IE<8 + // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); + }, + + // Position-in-collection + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "odd": createPositionalPseudo(function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } +}; + +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); +} + +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = Expr.filters = Expr.pseudos; +Expr.setFilters = new setFilters(); + +tokenize = Sizzle.tokenize = function( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || (match = rcomma.exec( soFar )) ) { + if ( match ) { + // Don't consume trailing commas as valid + soFar = soFar.slice( match[0].length ) || soFar; + } + groups.push( (tokens = []) ); + } + + matched = false; + + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + matched = match.shift(); + tokens.push({ + value: matched, + // Cast descendant combinators to space + type: match[0].replace( rtrim, " " ) + }); + soFar = soFar.slice( matched.length ); + } + + // Filters + for ( type in Expr.filter ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + (match = preFilters[ type ]( match ))) ) { + matched = match.shift(); + tokens.push({ + value: matched, + type: type, + matches: match + }); + soFar = soFar.slice( matched.length ); + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +}; + +function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[i].value; + } + return selector; +} + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + checkNonElements = base && dir === "parentNode", + doneName = done++; + + return combinator.first ? + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var oldCache, uniqueCache, outerCache, + newCache = [ dirruns, doneName ]; + + // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching + if ( xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ expando ] || (elem[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {}); + + if ( (oldCache = uniqueCache[ dir ]) && + oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { + + // Assign to newCache so results back-propagate to previous elements + return (newCache[ 2 ] = oldCache[ 2 ]); + } else { + // Reuse newcache so results back-propagate to previous elements + uniqueCache[ dir ] = newCache; + + // A match means we're done; a fail means we have to keep checking + if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { + return true; + } + } + } + } + } + }; +} + +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[i]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[0]; +} + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); + } + return results; +} + +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( (elem = unmatched[i]) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; +} + +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction(function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( (elem = temp[i]) ) { + matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) ) { + // Restore matcherIn since elem is not yet a final match + temp.push( (matcherIn[i] = elem) ); + } + } + postFinder( null, (matcherOut = []), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) && + (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { + + seed[temp] = !(results[temp] = elem); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + }); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[0].type ], + implicitRelative = leadingRelative || Expr.relative[" "], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + (checkContext = context).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + // Avoid hanging onto element (issue #299) + checkContext = null; + return ret; + } ]; + + for ( ; i < len; i++ ) { + if ( (matcher = Expr.relative[ tokens[i].type ]) ) { + matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; + } else { + matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[j].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( + // If the preceding token was a descendant combinator, insert an implicit any-element `*` + tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) + ).replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), + j < len && toSelector( tokens ) + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + var bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, outermost ) { + var elem, j, matcher, + matchedCount = 0, + i = "0", + unmatched = seed && [], + setMatched = [], + contextBackup = outermostContext, + // We must always have either seed elements or outermost context + elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), + len = elems.length; + + if ( outermost ) { + outermostContext = context === document || context || outermost; + } + + // Add elements passing elementMatchers directly to results + // Support: IE<9, Safari + // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id + for ( ; i !== len && (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + if ( !context && elem.ownerDocument !== document ) { + setDocument( elem ); + xml = !documentIsHTML; + } + while ( (matcher = elementMatchers[j++]) ) { + if ( matcher( elem, context || document, xml) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // `i` is now the count of elements visited above, and adding it to `matchedCount` + // makes the latter nonnegative. + matchedCount += i; + + // Apply set filters to unmatched elements + // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` + // equals `i`), unless we didn't visit _any_ elements in the above loop because we have + // no element matchers and no seed. + // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that + // case, which will result in a "00" `matchedCount` that differs from `i` but is also + // numerically zero. + if ( bySet && i !== matchedCount ) { + j = 0; + while ( (matcher = setMatchers[j++]) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !match ) { + match = tokenize( selector ); + } + i = match.length; + while ( i-- ) { + cached = matcherFromTokens( match[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + + // Save selector and tokenization + cached.selector = selector; + } + return cached; +}; + +/** + * A low-level selection function that works with Sizzle's compiled + * selector functions + * @param {String|Function} selector A selector or a pre-compiled + * selector function built with Sizzle.compile + * @param {Element} context + * @param {Array} [results] + * @param {Array} [seed] A set of elements to match against + */ +select = Sizzle.select = function( selector, context, results, seed ) { + var i, tokens, token, type, find, + compiled = typeof selector === "function" && selector, + match = !seed && tokenize( (selector = compiled.selector || selector) ); + + results = results || []; + + // Try to minimize operations if there is only one selector in the list and no seed + // (the latter of which guarantees us context) + if ( match.length === 1 ) { + + // Reduce context if the leading compound selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + support.getById && context.nodeType === 9 && documentIsHTML && + Expr.relative[ tokens[1].type ] ) { + + context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; + if ( !context ) { + return results; + + // Precompiled matchers will still verify ancestry, so step up a level + } else if ( compiled ) { + context = context.parentNode; + } + + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( runescape, funescape ), + rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } + + break; + } + } + } + } + + // Compile and execute a filtering function if one is not provided + // Provide `match` to avoid retokenization if we modified the selector above + ( compiled || compile( selector, match ) )( + seed, + context, + !documentIsHTML, + results, + !context || rsibling.test( selector ) && testContext( context.parentNode ) || context + ); + return results; +}; + +// One-time assignments + +// Sort stability +support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; + +// Support: Chrome 14-35+ +// Always assume duplicates if they aren't passed to the comparison function +support.detectDuplicates = !!hasDuplicate; + +// Initialize against the default document +setDocument(); + +// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) +// Detached nodes confoundingly follow *each other* +support.sortDetached = assert(function( div1 ) { + // Should return 1, but returns 4 (following) + return div1.compareDocumentPosition( document.createElement("div") ) & 1; +}); + +// Support: IE<8 +// Prevent attribute/property "interpolation" +// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !assert(function( div ) { + div.innerHTML = "<a href='#'></a>"; + return div.firstChild.getAttribute("href") === "#" ; +}) ) { + addHandle( "type|href|height|width", function( elem, name, isXML ) { + if ( !isXML ) { + return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); + } + }); +} + +// Support: IE<9 +// Use defaultValue in place of getAttribute("value") +if ( !support.attributes || !assert(function( div ) { + div.innerHTML = "<input/>"; + div.firstChild.setAttribute( "value", "" ); + return div.firstChild.getAttribute( "value" ) === ""; +}) ) { + addHandle( "value", function( elem, name, isXML ) { + if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { + return elem.defaultValue; + } + }); +} + +// Support: IE<9 +// Use getAttributeNode to fetch booleans when getAttribute lies +if ( !assert(function( div ) { + return div.getAttribute("disabled") == null; +}) ) { + addHandle( booleans, function( elem, name, isXML ) { + var val; + if ( !isXML ) { + return elem[ name ] === true ? name.toLowerCase() : + (val = elem.getAttributeNode( name )) && val.specified ? + val.value : + null; + } + }); +} + +return Sizzle; + +})( window ); + + + +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[ ":" ] = jQuery.expr.pseudos; +jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + + +var dir = function( elem, dir, until ) { + var matched = [], + truncate = until !== undefined; + + while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { + if ( elem.nodeType === 1 ) { + if ( truncate && jQuery( elem ).is( until ) ) { + break; + } + matched.push( elem ); + } + } + return matched; +}; + + +var siblings = function( n, elem ) { + var matched = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + matched.push( n ); + } + } + + return matched; +}; + + +var rneedsContext = jQuery.expr.match.needsContext; + +var rsingleTag = ( /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/ ); + + + +var risSimple = /^.[^:#\[\.,]*$/; + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, not ) { + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep( elements, function( elem, i ) { + /* jshint -W018 */ + return !!qualifier.call( elem, i, elem ) !== not; + } ); + + } + + if ( qualifier.nodeType ) { + return jQuery.grep( elements, function( elem ) { + return ( elem === qualifier ) !== not; + } ); + + } + + if ( typeof qualifier === "string" ) { + if ( risSimple.test( qualifier ) ) { + return jQuery.filter( qualifier, elements, not ); + } + + qualifier = jQuery.filter( qualifier, elements ); + } + + return jQuery.grep( elements, function( elem ) { + return ( indexOf.call( qualifier, elem ) > -1 ) !== not; + } ); +} + +jQuery.filter = function( expr, elems, not ) { + var elem = elems[ 0 ]; + + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 && elem.nodeType === 1 ? + jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : + jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + } ) ); +}; + +jQuery.fn.extend( { + find: function( selector ) { + var i, + len = this.length, + ret = [], + self = this; + + if ( typeof selector !== "string" ) { + return this.pushStack( jQuery( selector ).filter( function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + } ) ); + } + + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); + } + + // Needed because $( selector, context ) becomes $( context ).find( selector ) + ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); + ret.selector = this.selector ? this.selector + " " + selector : selector; + return ret; + }, + filter: function( selector ) { + return this.pushStack( winnow( this, selector || [], false ) ); + }, + not: function( selector ) { + return this.pushStack( winnow( this, selector || [], true ) ); + }, + is: function( selector ) { + return !!winnow( + this, + + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + typeof selector === "string" && rneedsContext.test( selector ) ? + jQuery( selector ) : + selector || [], + false + ).length; + } +} ); + + +// Initialize a jQuery object + + +// A central reference to the root jQuery(document) +var rootjQuery, + + // A simple way to check for HTML strings + // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) + // Strict HTML recognition (#11290: must start with <) + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, + + init = jQuery.fn.init = function( selector, context, root ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Method init() accepts an alternate rootjQuery + // so migrate can support jQuery.sub (gh-2101) + root = root || rootjQuery; + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector[ 0 ] === "<" && + selector[ selector.length - 1 ] === ">" && + selector.length >= 3 ) { + + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && ( match[ 1 ] || !context ) ) { + + // HANDLE: $(html) -> $(array) + if ( match[ 1 ] ) { + context = context instanceof jQuery ? context[ 0 ] : context; + + // Option to run scripts is true for back-compat + // Intentionally let the error be thrown if parseHTML is not present + jQuery.merge( this, jQuery.parseHTML( + match[ 1 ], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + + // Properties of context are called as methods if possible + if ( jQuery.isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } + + return this; + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[ 2 ] ); + + // Support: Blackberry 4.6 + // gEBID returns nodes no longer in the document (#6963) + if ( elem && elem.parentNode ) { + + // Inject the element directly into the jQuery object + this.length = 1; + this[ 0 ] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || root ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this.context = this[ 0 ] = selector; + this.length = 1; + return this; + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return root.ready !== undefined ? + root.ready( selector ) : + + // Execute immediately if ready is not present + selector( jQuery ); + } + + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }; + +// Give the init function the jQuery prototype for later instantiation +init.prototype = jQuery.fn; + +// Initialize central reference +rootjQuery = jQuery( document ); + + +var rparentsprev = /^(?:parents|prev(?:Until|All))/, + + // Methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend( { + has: function( target ) { + var targets = jQuery( target, this ), + l = targets.length; + + return this.filter( function() { + var i = 0; + for ( ; i < l; i++ ) { + if ( jQuery.contains( this, targets[ i ] ) ) { + return true; + } + } + } ); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + matched = [], + pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( ; i < l; i++ ) { + for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { + + // Always skip document fragments + if ( cur.nodeType < 11 && ( pos ? + pos.index( cur ) > -1 : + + // Don't pass non-elements to Sizzle + cur.nodeType === 1 && + jQuery.find.matchesSelector( cur, selectors ) ) ) { + + matched.push( cur ); + break; + } + } + } + + return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); + }, + + // Determine the position of an element within the set + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; + } + + // Index in selector + if ( typeof elem === "string" ) { + return indexOf.call( jQuery( elem ), this[ 0 ] ); + } + + // Locate the position of the desired element + return indexOf.call( this, + + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[ 0 ] : elem + ); + }, + + add: function( selector, context ) { + return this.pushStack( + jQuery.uniqueSort( + jQuery.merge( this.get(), jQuery( selector, context ) ) + ) + ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter( selector ) + ); + } +} ); + +function sibling( cur, dir ) { + while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} + return cur; +} + +jQuery.each( { + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return siblings( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return siblings( elem.firstChild ); + }, + contents: function( elem ) { + return elem.contentDocument || jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var matched = jQuery.map( this, fn, until ); + + if ( name.slice( -5 ) !== "Until" ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + matched = jQuery.filter( selector, matched ); + } + + if ( this.length > 1 ) { + + // Remove duplicates + if ( !guaranteedUnique[ name ] ) { + jQuery.uniqueSort( matched ); + } + + // Reverse order for parents* and prev-derivatives + if ( rparentsprev.test( name ) ) { + matched.reverse(); + } + } + + return this.pushStack( matched ); + }; +} ); +var rnotwhite = ( /\S+/g ); + + + +// Convert String-formatted options into Object-formatted ones +function createOptions( options ) { + var object = {}; + jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { + object[ flag ] = true; + } ); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + createOptions( options ) : + jQuery.extend( {}, options ); + + var // Flag to know if list is currently firing + firing, + + // Last fire value for non-forgettable lists + memory, + + // Flag to know if list was already fired + fired, + + // Flag to prevent firing + locked, + + // Actual callback list + list = [], + + // Queue of execution data for repeatable lists + queue = [], + + // Index of currently firing callback (modified by add/remove as needed) + firingIndex = -1, + + // Fire callbacks + fire = function() { + + // Enforce single-firing + locked = options.once; + + // Execute callbacks for all pending executions, + // respecting firingIndex overrides and runtime changes + fired = firing = true; + for ( ; queue.length; firingIndex = -1 ) { + memory = queue.shift(); + while ( ++firingIndex < list.length ) { + + // Run callback and check for early termination + if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && + options.stopOnFalse ) { + + // Jump to end and forget the data so .add doesn't re-fire + firingIndex = list.length; + memory = false; + } + } + } + + // Forget the data if we're done with it + if ( !options.memory ) { + memory = false; + } + + firing = false; + + // Clean up if we're done firing for good + if ( locked ) { + + // Keep an empty list if we have data for future add calls + if ( memory ) { + list = []; + + // Otherwise, this object is spent + } else { + list = ""; + } + } + }, + + // Actual Callbacks object + self = { + + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + + // If we have memory from a past run, we should fire after adding + if ( memory && !firing ) { + firingIndex = list.length - 1; + queue.push( memory ); + } + + ( function add( args ) { + jQuery.each( args, function( _, arg ) { + if ( jQuery.isFunction( arg ) ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) { + + // Inspect recursively + add( arg ); + } + } ); + } )( arguments ); + + if ( memory && !firing ) { + fire(); + } + } + return this; + }, + + // Remove a callback from the list + remove: function() { + jQuery.each( arguments, function( _, arg ) { + var index; + while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + + // Handle firing indexes + if ( index <= firingIndex ) { + firingIndex--; + } + } + } ); + return this; + }, + + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? + jQuery.inArray( fn, list ) > -1 : + list.length > 0; + }, + + // Remove all callbacks from the list + empty: function() { + if ( list ) { + list = []; + } + return this; + }, + + // Disable .fire and .add + // Abort any current/pending executions + // Clear all callbacks and values + disable: function() { + locked = queue = []; + list = memory = ""; + return this; + }, + disabled: function() { + return !list; + }, + + // Disable .fire + // Also disable .add unless we have memory (since it would have no effect) + // Abort any pending executions + lock: function() { + locked = queue = []; + if ( !memory ) { + list = memory = ""; + } + return this; + }, + locked: function() { + return !!locked; + }, + + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( !locked ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + queue.push( args ); + if ( !firing ) { + fire(); + } + } + return this; + }, + + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; +}; + + +jQuery.extend( { + + Deferred: function( func ) { + var tuples = [ + + // action, add listener, listener list, final state + [ "resolve", "done", jQuery.Callbacks( "once memory" ), "resolved" ], + [ "reject", "fail", jQuery.Callbacks( "once memory" ), "rejected" ], + [ "notify", "progress", jQuery.Callbacks( "memory" ) ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + then: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + return jQuery.Deferred( function( newDefer ) { + jQuery.each( tuples, function( i, tuple ) { + var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; + + // deferred[ done | fail | progress ] for forwarding actions to newDefer + deferred[ tuple[ 1 ] ]( function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise() + .progress( newDefer.notify ) + .done( newDefer.resolve ) + .fail( newDefer.reject ); + } else { + newDefer[ tuple[ 0 ] + "With" ]( + this === promise ? newDefer.promise() : this, + fn ? [ returned ] : arguments + ); + } + } ); + } ); + fns = null; + } ).promise(); + }, + + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Keep pipe for back-compat + promise.pipe = promise.then; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 3 ]; + + // promise[ done | fail | progress ] = list.add + promise[ tuple[ 1 ] ] = list.add; + + // Handle state + if ( stateString ) { + list.add( function() { + + // state = [ resolved | rejected ] + state = stateString; + + // [ reject_list | resolve_list ].disable; progress_list.lock + }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); + } + + // deferred[ resolve | reject | notify ] + deferred[ tuple[ 0 ] ] = function() { + deferred[ tuple[ 0 ] + "With" ]( this === deferred ? promise : this, arguments ); + return this; + }; + deferred[ tuple[ 0 ] + "With" ] = list.fireWith; + } ); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( subordinate /* , ..., subordinateN */ ) { + var i = 0, + resolveValues = slice.call( arguments ), + length = resolveValues.length, + + // the count of uncompleted subordinates + remaining = length !== 1 || + ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, + + // the master Deferred. + // If resolveValues consist of only a single Deferred, just use that. + deferred = remaining === 1 ? subordinate : jQuery.Deferred(), + + // Update function for both resolve and progress values + updateFunc = function( i, contexts, values ) { + return function( value ) { + contexts[ i ] = this; + values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; + if ( values === progressValues ) { + deferred.notifyWith( contexts, values ); + } else if ( !( --remaining ) ) { + deferred.resolveWith( contexts, values ); + } + }; + }, + + progressValues, progressContexts, resolveContexts; + + // Add listeners to Deferred subordinates; treat others as resolved + if ( length > 1 ) { + progressValues = new Array( length ); + progressContexts = new Array( length ); + resolveContexts = new Array( length ); + for ( ; i < length; i++ ) { + if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { + resolveValues[ i ].promise() + .progress( updateFunc( i, progressContexts, progressValues ) ) + .done( updateFunc( i, resolveContexts, resolveValues ) ) + .fail( deferred.reject ); + } else { + --remaining; + } + } + } + + // If we're not waiting on anything, resolve the master + if ( !remaining ) { + deferred.resolveWith( resolveContexts, resolveValues ); + } + + return deferred.promise(); + } +} ); + + +// The deferred used on DOM ready +var readyList; + +jQuery.fn.ready = function( fn ) { + + // Add the callback + jQuery.ready.promise().done( fn ); + + return this; +}; + +jQuery.extend( { + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.triggerHandler ) { + jQuery( document ).triggerHandler( "ready" ); + jQuery( document ).off( "ready" ); + } + } +} ); + +/** + * The ready event handler and self cleanup method + */ +function completed() { + document.removeEventListener( "DOMContentLoaded", completed ); + window.removeEventListener( "load", completed ); + jQuery.ready(); +} + +jQuery.ready.promise = function( obj ) { + if ( !readyList ) { + + readyList = jQuery.Deferred(); + + // Catch cases where $(document).ready() is called + // after the browser event has already occurred. + // Support: IE9-10 only + // Older IE sometimes signals "interactive" too soon + if ( document.readyState === "complete" || + ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { + + // Handle it asynchronously to allow scripts the opportunity to delay ready + window.setTimeout( jQuery.ready ); + + } else { + + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed ); + } + } + return readyList.promise( obj ); +}; + +// Kick off the DOM ready check even if the user does not +jQuery.ready.promise(); + + + + +// Multifunctional method to get and set values of a collection +// The value/s can optionally be executed if it's a function +var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + len = elems.length, + bulk = key == null; + + // Sets many values + if ( jQuery.type( key ) === "object" ) { + chainable = true; + for ( i in key ) { + access( elems, fn, i, key[ i ], true, emptyGet, raw ); + } + + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( !jQuery.isFunction( value ) ) { + raw = true; + } + + if ( bulk ) { + + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, key, value ) { + return bulk.call( jQuery( elem ), value ); + }; + } + } + + if ( fn ) { + for ( ; i < len; i++ ) { + fn( + elems[ i ], key, raw ? + value : + value.call( elems[ i ], i, fn( elems[ i ], key ) ) + ); + } + } + } + + return chainable ? + elems : + + // Gets + bulk ? + fn.call( elems ) : + len ? fn( elems[ 0 ], key ) : emptyGet; +}; +var acceptData = function( owner ) { + + // Accepts only: + // - Node + // - Node.ELEMENT_NODE + // - Node.DOCUMENT_NODE + // - Object + // - Any + /* jshint -W018 */ + return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); +}; + + + + +function Data() { + this.expando = jQuery.expando + Data.uid++; +} + +Data.uid = 1; + +Data.prototype = { + + register: function( owner, initial ) { + var value = initial || {}; + + // If it is a node unlikely to be stringify-ed or looped over + // use plain assignment + if ( owner.nodeType ) { + owner[ this.expando ] = value; + + // Otherwise secure it in a non-enumerable, non-writable property + // configurability must be true to allow the property to be + // deleted with the delete operator + } else { + Object.defineProperty( owner, this.expando, { + value: value, + writable: true, + configurable: true + } ); + } + return owner[ this.expando ]; + }, + cache: function( owner ) { + + // We can accept data for non-element nodes in modern browsers, + // but we should not, see #8335. + // Always return an empty object. + if ( !acceptData( owner ) ) { + return {}; + } + + // Check if the owner object already has a cache + var value = owner[ this.expando ]; + + // If not, create one + if ( !value ) { + value = {}; + + // We can accept data for non-element nodes in modern browsers, + // but we should not, see #8335. + // Always return an empty object. + if ( acceptData( owner ) ) { + + // If it is a node unlikely to be stringify-ed or looped over + // use plain assignment + if ( owner.nodeType ) { + owner[ this.expando ] = value; + + // Otherwise secure it in a non-enumerable property + // configurable must be true to allow the property to be + // deleted when data is removed + } else { + Object.defineProperty( owner, this.expando, { + value: value, + configurable: true + } ); + } + } + } + + return value; + }, + set: function( owner, data, value ) { + var prop, + cache = this.cache( owner ); + + // Handle: [ owner, key, value ] args + if ( typeof data === "string" ) { + cache[ data ] = value; + + // Handle: [ owner, { properties } ] args + } else { + + // Copy the properties one-by-one to the cache object + for ( prop in data ) { + cache[ prop ] = data[ prop ]; + } + } + return cache; + }, + get: function( owner, key ) { + return key === undefined ? + this.cache( owner ) : + owner[ this.expando ] && owner[ this.expando ][ key ]; + }, + access: function( owner, key, value ) { + var stored; + + // In cases where either: + // + // 1. No key was specified + // 2. A string key was specified, but no value provided + // + // Take the "read" path and allow the get method to determine + // which value to return, respectively either: + // + // 1. The entire cache object + // 2. The data stored at the key + // + if ( key === undefined || + ( ( key && typeof key === "string" ) && value === undefined ) ) { + + stored = this.get( owner, key ); + + return stored !== undefined ? + stored : this.get( owner, jQuery.camelCase( key ) ); + } + + // When the key is not a string, or both a key and value + // are specified, set or extend (existing objects) with either: + // + // 1. An object of properties + // 2. A key and value + // + this.set( owner, key, value ); + + // Since the "set" path can have two possible entry points + // return the expected data based on which path was taken[*] + return value !== undefined ? value : key; + }, + remove: function( owner, key ) { + var i, name, camel, + cache = owner[ this.expando ]; + + if ( cache === undefined ) { + return; + } + + if ( key === undefined ) { + this.register( owner ); + + } else { + + // Support array or space separated string of keys + if ( jQuery.isArray( key ) ) { + + // If "name" is an array of keys... + // When data is initially created, via ("key", "val") signature, + // keys will be converted to camelCase. + // Since there is no way to tell _how_ a key was added, remove + // both plain key and camelCase key. #12786 + // This will only penalize the array argument path. + name = key.concat( key.map( jQuery.camelCase ) ); + } else { + camel = jQuery.camelCase( key ); + + // Try the string as a key before any manipulation + if ( key in cache ) { + name = [ key, camel ]; + } else { + + // If a key with the spaces exists, use it. + // Otherwise, create an array by matching non-whitespace + name = camel; + name = name in cache ? + [ name ] : ( name.match( rnotwhite ) || [] ); + } + } + + i = name.length; + + while ( i-- ) { + delete cache[ name[ i ] ]; + } + } + + // Remove the expando if there's no more data + if ( key === undefined || jQuery.isEmptyObject( cache ) ) { + + // Support: Chrome <= 35-45+ + // Webkit & Blink performance suffers when deleting properties + // from DOM nodes, so set to undefined instead + // https://code.google.com/p/chromium/issues/detail?id=378607 + if ( owner.nodeType ) { + owner[ this.expando ] = undefined; + } else { + delete owner[ this.expando ]; + } + } + }, + hasData: function( owner ) { + var cache = owner[ this.expando ]; + return cache !== undefined && !jQuery.isEmptyObject( cache ); + } +}; +var dataPriv = new Data(); + +var dataUser = new Data(); + + + +// Implementation Summary +// +// 1. Enforce API surface and semantic compatibility with 1.9.x branch +// 2. Improve the module's maintainability by reducing the storage +// paths to a single mechanism. +// 3. Use the same single mechanism to support "private" and "user" data. +// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) +// 5. Avoid exposing implementation details on user objects (eg. expando properties) +// 6. Provide a clear path for implementation upgrade to WeakMap in 2014 + +var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, + rmultiDash = /[A-Z]/g; + +function dataAttr( elem, key, data ) { + var name; + + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + + // Only convert to a number if it doesn't change the string + +data + "" === data ? +data : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch ( e ) {} + + // Make sure we set the data so it isn't changed later + dataUser.set( elem, key, data ); + } else { + data = undefined; + } + } + return data; +} + +jQuery.extend( { + hasData: function( elem ) { + return dataUser.hasData( elem ) || dataPriv.hasData( elem ); + }, + + data: function( elem, name, data ) { + return dataUser.access( elem, name, data ); + }, + + removeData: function( elem, name ) { + dataUser.remove( elem, name ); + }, + + // TODO: Now that all calls to _data and _removeData have been replaced + // with direct calls to dataPriv methods, these can be deprecated. + _data: function( elem, name, data ) { + return dataPriv.access( elem, name, data ); + }, + + _removeData: function( elem, name ) { + dataPriv.remove( elem, name ); + } +} ); + +jQuery.fn.extend( { + data: function( key, value ) { + var i, name, data, + elem = this[ 0 ], + attrs = elem && elem.attributes; + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = dataUser.get( elem ); + + if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { + i = attrs.length; + while ( i-- ) { + + // Support: IE11+ + // The attrs elements can be null (#14894) + if ( attrs[ i ] ) { + name = attrs[ i ].name; + if ( name.indexOf( "data-" ) === 0 ) { + name = jQuery.camelCase( name.slice( 5 ) ); + dataAttr( elem, name, data[ name ] ); + } + } + } + dataPriv.set( elem, "hasDataAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each( function() { + dataUser.set( this, key ); + } ); + } + + return access( this, function( value ) { + var data, camelKey; + + // The calling jQuery object (element matches) is not empty + // (and therefore has an element appears at this[ 0 ]) and the + // `value` parameter was not undefined. An empty jQuery object + // will result in `undefined` for elem = this[ 0 ] which will + // throw an exception if an attempt to read a data cache is made. + if ( elem && value === undefined ) { + + // Attempt to get data from the cache + // with the key as-is + data = dataUser.get( elem, key ) || + + // Try to find dashed key if it exists (gh-2779) + // This is for 2.2.x only + dataUser.get( elem, key.replace( rmultiDash, "-$&" ).toLowerCase() ); + + if ( data !== undefined ) { + return data; + } + + camelKey = jQuery.camelCase( key ); + + // Attempt to get data from the cache + // with the key camelized + data = dataUser.get( elem, camelKey ); + if ( data !== undefined ) { + return data; + } + + // Attempt to "discover" the data in + // HTML5 custom data-* attrs + data = dataAttr( elem, camelKey, undefined ); + if ( data !== undefined ) { + return data; + } + + // We tried really hard, but the data doesn't exist. + return; + } + + // Set the data... + camelKey = jQuery.camelCase( key ); + this.each( function() { + + // First, attempt to store a copy or reference of any + // data that might've been store with a camelCased key. + var data = dataUser.get( this, camelKey ); + + // For HTML5 data-* attribute interop, we have to + // store property names with dashes in a camelCase form. + // This might not apply to all properties...* + dataUser.set( this, camelKey, value ); + + // *... In the case of properties that might _actually_ + // have dashes, we need to also store a copy of that + // unchanged property. + if ( key.indexOf( "-" ) > -1 && data !== undefined ) { + dataUser.set( this, key, value ); + } + } ); + }, null, value, arguments.length > 1, null, true ); + }, + + removeData: function( key ) { + return this.each( function() { + dataUser.remove( this, key ); + } ); + } +} ); + + +jQuery.extend( { + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = dataPriv.get( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || jQuery.isArray( data ) ) { + queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // Clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // Not public - generate a queueHooks object, or return the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { + empty: jQuery.Callbacks( "once memory" ).add( function() { + dataPriv.remove( elem, [ type + "queue", key ] ); + } ) + } ); + } +} ); + +jQuery.fn.extend( { + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[ 0 ], type ); + } + + return data === undefined ? + this : + this.each( function() { + var queue = jQuery.queue( this, type, data ); + + // Ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + } ); + }, + dequeue: function( type ) { + return this.each( function() { + jQuery.dequeue( this, type ); + } ); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while ( i-- ) { + tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +} ); +var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; + +var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); + + +var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; + +var isHidden = function( elem, el ) { + + // isHidden might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + return jQuery.css( elem, "display" ) === "none" || + !jQuery.contains( elem.ownerDocument, elem ); + }; + + + +function adjustCSS( elem, prop, valueParts, tween ) { + var adjusted, + scale = 1, + maxIterations = 20, + currentValue = tween ? + function() { return tween.cur(); } : + function() { return jQuery.css( elem, prop, "" ); }, + initial = currentValue(), + unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), + + // Starting value computation is required for potential unit mismatches + initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && + rcssNum.exec( jQuery.css( elem, prop ) ); + + if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { + + // Trust units reported by jQuery.css + unit = unit || initialInUnit[ 3 ]; + + // Make sure we update the tween properties later on + valueParts = valueParts || []; + + // Iteratively approximate from a nonzero starting point + initialInUnit = +initial || 1; + + do { + + // If previous iteration zeroed out, double until we get *something*. + // Use string for doubling so we don't accidentally see scale as unchanged below + scale = scale || ".5"; + + // Adjust and apply + initialInUnit = initialInUnit / scale; + jQuery.style( elem, prop, initialInUnit + unit ); + + // Update scale, tolerating zero or NaN from tween.cur() + // Break the loop if scale is unchanged or perfect, or if we've just had enough. + } while ( + scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations + ); + } + + if ( valueParts ) { + initialInUnit = +initialInUnit || +initial || 0; + + // Apply relative offset (+=/-=) if specified + adjusted = valueParts[ 1 ] ? + initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : + +valueParts[ 2 ]; + if ( tween ) { + tween.unit = unit; + tween.start = initialInUnit; + tween.end = adjusted; + } + } + return adjusted; +} +var rcheckableType = ( /^(?:checkbox|radio)$/i ); + +var rtagName = ( /<([\w:-]+)/ ); + +var rscriptType = ( /^$|\/(?:java|ecma)script/i ); + + + +// We have to close these tags to support XHTML (#13200) +var wrapMap = { + + // Support: IE9 + option: [ 1, "<select multiple='multiple'>", "</select>" ], + + // XHTML parsers do not magically insert elements in the + // same way that tag soup parsers do. So we cannot shorten + // this by omitting <tbody> or other required elements. + thead: [ 1, "<table>", "</table>" ], + col: [ 2, "<table><colgroup>", "</colgroup></table>" ], + tr: [ 2, "<table><tbody>", "</tbody></table>" ], + td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], + + _default: [ 0, "", "" ] +}; + +// Support: IE9 +wrapMap.optgroup = wrapMap.option; + +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + + +function getAll( context, tag ) { + + // Support: IE9-11+ + // Use typeof to avoid zero-argument method invocation on host objects (#15151) + var ret = typeof context.getElementsByTagName !== "undefined" ? + context.getElementsByTagName( tag || "*" ) : + typeof context.querySelectorAll !== "undefined" ? + context.querySelectorAll( tag || "*" ) : + []; + + return tag === undefined || tag && jQuery.nodeName( context, tag ) ? + jQuery.merge( [ context ], ret ) : + ret; +} + + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + dataPriv.set( + elems[ i ], + "globalEval", + !refElements || dataPriv.get( refElements[ i ], "globalEval" ) + ); + } +} + + +var rhtml = /<|&#?\w+;/; + +function buildFragment( elems, context, scripts, selection, ignored ) { + var elem, tmp, tag, wrap, contains, j, + fragment = context.createDocumentFragment(), + nodes = [], + i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( jQuery.type( elem ) === "object" ) { + + // Support: Android<4.1, PhantomJS<2 + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); + + // Deserialize a standard representation + tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; + + // Descend through wrappers to the right content + j = wrap[ 0 ]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Support: Android<4.1, PhantomJS<2 + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, tmp.childNodes ); + + // Remember the top-level container + tmp = fragment.firstChild; + + // Ensure the created nodes are orphaned (#12392) + tmp.textContent = ""; + } + } + } + + // Remove wrapper from fragment + fragment.textContent = ""; + + i = 0; + while ( ( elem = nodes[ i++ ] ) ) { + + // Skip elements already in the context collection (trac-4087) + if ( selection && jQuery.inArray( elem, selection ) > -1 ) { + if ( ignored ) { + ignored.push( elem ); + } + continue; + } + + contains = jQuery.contains( elem.ownerDocument, elem ); + + // Append to fragment + tmp = getAll( fragment.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( contains ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( ( elem = tmp[ j++ ] ) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + return fragment; +} + + +( function() { + var fragment = document.createDocumentFragment(), + div = fragment.appendChild( document.createElement( "div" ) ), + input = document.createElement( "input" ); + + // Support: Android 4.0-4.3, Safari<=5.1 + // Check state lost if the name is set (#11217) + // Support: Windows Web Apps (WWA) + // `name` and `type` must use .setAttribute for WWA (#14901) + input.setAttribute( "type", "radio" ); + input.setAttribute( "checked", "checked" ); + input.setAttribute( "name", "t" ); + + div.appendChild( input ); + + // Support: Safari<=5.1, Android<4.2 + // Older WebKit doesn't clone checked state correctly in fragments + support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Support: IE<=11+ + // Make sure textarea (and checkbox) defaultValue is properly cloned + div.innerHTML = "<textarea>x</textarea>"; + support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; +} )(); + + +var + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, + rtypenamespace = /^([^.]*)(?:\.(.+)|)/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +// Support: IE9 +// See #13393 for more info +function safeActiveElement() { + try { + return document.activeElement; + } catch ( err ) { } +} + +function on( elem, types, selector, data, fn, one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + on( elem, type, selector, data, types[ type ], one ); + } + return elem; + } + + if ( data == null && fn == null ) { + + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return this; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return elem.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + } ); +} + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + global: {}, + + add: function( elem, types, handler, data, selector ) { + + var handleObjIn, eventHandle, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.get( elem ); + + // Don't attach events to noData or text/comment nodes (but allow plain objects) + if ( !elemData ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + if ( !( events = elemData.events ) ) { + events = elemData.events = {}; + } + if ( !( eventHandle = elemData.handle ) ) { + eventHandle = elemData.handle = function( e ) { + + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? + jQuery.event.dispatch.apply( elem, arguments ) : undefined; + }; + } + + // Handle multiple events separated by a space + types = ( types || "" ).match( rnotwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // There *must* be a type, no attaching namespace-only handlers + if ( !type ) { + continue; + } + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend( { + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join( "." ) + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !( handlers = events[ type ] ) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener if the special events handler returns false + if ( !special.setup || + special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var j, origCount, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); + + if ( !elemData || !( events = elemData.events ) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( rnotwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[ 2 ] && + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || + selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || + special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove data and the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + dataPriv.remove( elem, "handle events" ); + } + }, + + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event ); + + var i, j, ret, matched, handleObj, + handlerQueue = [], + args = slice.call( arguments ), + handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[ 0 ] = event; + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; + + j = 0; + while ( ( handleObj = matched.handlers[ j++ ] ) && + !event.isImmediatePropagationStopped() ) { + + // Triggered event must either 1) have no namespace, or 2) have namespace(s) + // a subset or equal to those in the bound event (both can have no namespace). + if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || + handleObj.handler ).apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( ( event.result = ret ) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var i, matches, sel, handleObj, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Support (at least): Chrome, IE9 + // Find delegate handlers + // Black-hole SVG <use> instance trees (#13180) + // + // Support: Firefox<=42+ + // Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343) + if ( delegateCount && cur.nodeType && + ( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) { + + for ( ; cur !== this; cur = cur.parentNode || this ) { + + // Don't check non-elements (#13208) + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.nodeType === 1 && ( cur.disabled !== true || event.type !== "click" ) ) { + matches = []; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; + + if ( matches[ sel ] === undefined ) { + matches[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) > -1 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matches[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push( { elem: cur, handlers: matches } ); + } + } + } + } + + // Add the remaining (directly-bound) handlers + if ( delegateCount < handlers.length ) { + handlerQueue.push( { elem: this, handlers: handlers.slice( delegateCount ) } ); + } + + return handlerQueue; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + props: ( "altKey bubbles cancelable ctrlKey currentTarget detail eventPhase " + + "metaKey relatedTarget shiftKey target timeStamp view which" ).split( " " ), + + fixHooks: {}, + + keyHooks: { + props: "char charCode key keyCode".split( " " ), + filter: function( event, original ) { + + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } + + return event; + } + }, + + mouseHooks: { + props: ( "button buttons clientX clientY offsetX offsetY pageX pageY " + + "screenX screenY toElement" ).split( " " ), + filter: function( event, original ) { + var eventDoc, doc, body, + button = original.button; + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; + + event.pageX = original.clientX + + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - + ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - + ( doc && doc.clientTop || body && body.clientTop || 0 ); + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event; + } + }, + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // Create a writable copy of the event object and normalize some properties + var i, prop, copy, + type = event.type, + originalEvent = event, + fixHook = this.fixHooks[ type ]; + + if ( !fixHook ) { + this.fixHooks[ type ] = fixHook = + rmouseEvent.test( type ) ? this.mouseHooks : + rkeyEvent.test( type ) ? this.keyHooks : + {}; + } + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = new jQuery.Event( originalEvent ); + + i = copy.length; + while ( i-- ) { + prop = copy[ i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Support: Cordova 2.5 (WebKit) (#13255) + // All events should have a target; Cordova deviceready doesn't + if ( !event.target ) { + event.target = document; + } + + // Support: Safari 6.0+, Chrome<28 + // Target should not be a text node (#504, #13143) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; + }, + + special: { + load: { + + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + focus: { + + // Fire native event if possible so blur/focus sequence is correct + trigger: function() { + if ( this !== safeActiveElement() && this.focus ) { + this.focus(); + return false; + } + }, + delegateType: "focusin" + }, + blur: { + trigger: function() { + if ( this === safeActiveElement() && this.blur ) { + this.blur(); + return false; + } + }, + delegateType: "focusout" + }, + click: { + + // For checkbox, fire native event so checked state will be right + trigger: function() { + if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { + this.click(); + return false; + } + }, + + // For cross-browser consistency, don't fire native .click() on links + _default: function( event ) { + return jQuery.nodeName( event.target, "a" ); + } + }, + + beforeunload: { + postDispatch: function( event ) { + + // Support: Firefox 20+ + // Firefox doesn't alert if the returnValue field is not set. + if ( event.result !== undefined && event.originalEvent ) { + event.originalEvent.returnValue = event.result; + } + } + } + } +}; + +jQuery.removeEvent = function( elem, type, handle ) { + + // This "if" is needed for plain objects + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle ); + } +}; + +jQuery.Event = function( src, props ) { + + // Allow instantiation without the 'new' keyword + if ( !( this instanceof jQuery.Event ) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = src.defaultPrevented || + src.defaultPrevented === undefined && + + // Support: Android<4.0 + src.returnValue === false ? + returnTrue : + returnFalse; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + constructor: jQuery.Event, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + + if ( e ) { + e.preventDefault(); + } + }, + stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + + if ( e ) { + e.stopPropagation(); + } + }, + stopImmediatePropagation: function() { + var e = this.originalEvent; + + this.isImmediatePropagationStopped = returnTrue; + + if ( e ) { + e.stopImmediatePropagation(); + } + + this.stopPropagation(); + } +}; + +// Create mouseenter/leave events using mouseover/out and event-time checks +// so that event delegation works in jQuery. +// Do the same for pointerenter/pointerleave and pointerover/pointerout +// +// Support: Safari 7 only +// Safari sends mouseenter too often; see: +// https://code.google.com/p/chromium/issues/detail?id=470258 +// for the description of the bug (it existed in older Chrome versions as well). +jQuery.each( { + mouseenter: "mouseover", + mouseleave: "mouseout", + pointerenter: "pointerover", + pointerleave: "pointerout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mouseenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +} ); + +jQuery.fn.extend( { + on: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn ); + }, + one: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? + handleObj.origType + "." + handleObj.namespace : + handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each( function() { + jQuery.event.remove( this, types, fn, selector ); + } ); + } +} ); + + +var + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi, + + // Support: IE 10-11, Edge 10240+ + // In IE/Edge using regex groups here causes severe slowdowns. + // See https://connect.microsoft.com/IE/feedback/details/1736512/ + rnoInnerhtml = /<script|<style|<link/i, + + // checked="checked" or checked + rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, + rscriptTypeMasked = /^true\/(.*)/, + rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g; + +function manipulationTarget( elem, content ) { + if ( jQuery.nodeName( elem, "table" ) && + jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { + + return elem.getElementsByTagName( "tbody" )[ 0 ] || elem; + } + + return elem; +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + var match = rscriptTypeMasked.exec( elem.type ); + + if ( match ) { + elem.type = match[ 1 ]; + } else { + elem.removeAttribute( "type" ); + } + + return elem; +} + +function cloneCopyEvent( src, dest ) { + var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; + + if ( dest.nodeType !== 1 ) { + return; + } + + // 1. Copy private data: events, handlers, etc. + if ( dataPriv.hasData( src ) ) { + pdataOld = dataPriv.access( src ); + pdataCur = dataPriv.set( dest, pdataOld ); + events = pdataOld.events; + + if ( events ) { + delete pdataCur.handle; + pdataCur.events = {}; + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + } + + // 2. Copy user data + if ( dataUser.hasData( src ) ) { + udataOld = dataUser.access( src ); + udataCur = jQuery.extend( {}, udataOld ); + + dataUser.set( dest, udataCur ); + } +} + +// Fix IE bugs, see support tests +function fixInput( src, dest ) { + var nodeName = dest.nodeName.toLowerCase(); + + // Fails to persist the checked state of a cloned checkbox or radio button. + if ( nodeName === "input" && rcheckableType.test( src.type ) ) { + dest.checked = src.checked; + + // Fails to return the selected option to the default selected state when cloning options + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } +} + +function domManip( collection, args, callback, ignored ) { + + // Flatten any nested arrays + args = concat.apply( [], args ); + + var fragment, first, scripts, hasScripts, node, doc, + i = 0, + l = collection.length, + iNoClone = l - 1, + value = args[ 0 ], + isFunction = jQuery.isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( isFunction || + ( l > 1 && typeof value === "string" && + !support.checkClone && rchecked.test( value ) ) ) { + return collection.each( function( index ) { + var self = collection.eq( index ); + if ( isFunction ) { + args[ 0 ] = value.call( this, index, self.html() ); + } + domManip( self, args, callback, ignored ); + } ); + } + + if ( l ) { + fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + // Require either new content or an interest in ignored elements to invoke the callback + if ( first || ignored ) { + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item + // instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + + // Support: Android<4.1, PhantomJS<2 + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( collection[ i ], node, i ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Reenable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !dataPriv.access( node, "globalEval" ) && + jQuery.contains( doc, node ) ) { + + if ( node.src ) { + + // Optional AJAX dependency, but won't run scripts if not present + if ( jQuery._evalUrl ) { + jQuery._evalUrl( node.src ); + } + } else { + jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); + } + } + } + } + } + } + + return collection; +} + +function remove( elem, selector, keepData ) { + var node, + nodes = selector ? jQuery.filter( selector, elem ) : elem, + i = 0; + + for ( ; ( node = nodes[ i ] ) != null; i++ ) { + if ( !keepData && node.nodeType === 1 ) { + jQuery.cleanData( getAll( node ) ); + } + + if ( node.parentNode ) { + if ( keepData && jQuery.contains( node.ownerDocument, node ) ) { + setGlobalEval( getAll( node, "script" ) ); + } + node.parentNode.removeChild( node ); + } + } + + return elem; +} + +jQuery.extend( { + htmlPrefilter: function( html ) { + return html.replace( rxhtmlTag, "<$1></$2>" ); + }, + + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var i, l, srcElements, destElements, + clone = elem.cloneNode( true ), + inPage = jQuery.contains( elem.ownerDocument, elem ); + + // Fix IE cloning issues + if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && + !jQuery.isXMLDoc( elem ) ) { + + // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + fixInput( srcElements[ i ], destElements[ i ] ); + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + if ( deepDataAndEvents ) { + srcElements = srcElements || getAll( elem ); + destElements = destElements || getAll( clone ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + cloneCopyEvent( srcElements[ i ], destElements[ i ] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + // Return the cloned set + return clone; + }, + + cleanData: function( elems ) { + var data, elem, type, + special = jQuery.event.special, + i = 0; + + for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { + if ( acceptData( elem ) ) { + if ( ( data = elem[ dataPriv.expando ] ) ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + + // Support: Chrome <= 35-45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataPriv.expando ] = undefined; + } + if ( elem[ dataUser.expando ] ) { + + // Support: Chrome <= 35-45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataUser.expando ] = undefined; + } + } + } + } +} ); + +jQuery.fn.extend( { + + // Keep domManip exposed until 3.0 (gh-2225) + domManip: domManip, + + detach: function( selector ) { + return remove( this, selector, true ); + }, + + remove: function( selector ) { + return remove( this, selector ); + }, + + text: function( value ) { + return access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().each( function() { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + this.textContent = value; + } + } ); + }, null, value, arguments.length ); + }, + + append: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.appendChild( elem ); + } + } ); + }, + + prepend: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.insertBefore( elem, target.firstChild ); + } + } ); + }, + + before: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + } ); + }, + + after: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + } ); + }, + + empty: function() { + var elem, + i = 0; + + for ( ; ( elem = this[ i ] ) != null; i++ ) { + if ( elem.nodeType === 1 ) { + + // Prevent memory leaks + jQuery.cleanData( getAll( elem, false ) ); + + // Remove any remaining nodes + elem.textContent = ""; + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map( function() { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + } ); + }, + + html: function( value ) { + return access( this, function( value ) { + var elem = this[ 0 ] || {}, + i = 0, + l = this.length; + + if ( value === undefined && elem.nodeType === 1 ) { + return elem.innerHTML; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { + + value = jQuery.htmlPrefilter( value ); + + try { + for ( ; i < l; i++ ) { + elem = this[ i ] || {}; + + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch ( e ) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function() { + var ignored = []; + + // Make the changes, replacing each non-ignored context element with the new content + return domManip( this, arguments, function( elem ) { + var parent = this.parentNode; + + if ( jQuery.inArray( this, ignored ) < 0 ) { + jQuery.cleanData( getAll( this ) ); + if ( parent ) { + parent.replaceChild( elem, this ); + } + } + + // Force callback invocation + }, ignored ); + } +} ); + +jQuery.each( { + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1, + i = 0; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone( true ); + jQuery( insert[ i ] )[ original ]( elems ); + + // Support: QtWebKit + // .get() because push.apply(_, arraylike) throws + push.apply( ret, elems.get() ); + } + + return this.pushStack( ret ); + }; +} ); + + +var iframe, + elemdisplay = { + + // Support: Firefox + // We have to pre-define these values for FF (#10227) + HTML: "block", + BODY: "block" + }; + +/** + * Retrieve the actual display of a element + * @param {String} name nodeName of the element + * @param {Object} doc Document object + */ + +// Called only from within defaultDisplay +function actualDisplay( name, doc ) { + var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), + + display = jQuery.css( elem[ 0 ], "display" ); + + // We don't have any data stored on the element, + // so use "detach" method as fast way to get rid of the element + elem.detach(); + + return display; +} + +/** + * Try to determine the default display value of an element + * @param {String} nodeName + */ +function defaultDisplay( nodeName ) { + var doc = document, + display = elemdisplay[ nodeName ]; + + if ( !display ) { + display = actualDisplay( nodeName, doc ); + + // If the simple way fails, read from inside an iframe + if ( display === "none" || !display ) { + + // Use the already-created iframe if possible + iframe = ( iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" ) ) + .appendTo( doc.documentElement ); + + // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse + doc = iframe[ 0 ].contentDocument; + + // Support: IE + doc.write(); + doc.close(); + + display = actualDisplay( nodeName, doc ); + iframe.detach(); + } + + // Store the correct default display + elemdisplay[ nodeName ] = display; + } + + return display; +} +var rmargin = ( /^margin/ ); + +var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); + +var getStyles = function( elem ) { + + // Support: IE<=11+, Firefox<=30+ (#15098, #14150) + // IE throws on elements created in popups + // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" + var view = elem.ownerDocument.defaultView; + + if ( !view.opener ) { + view = window; + } + + return view.getComputedStyle( elem ); + }; + +var swap = function( elem, options, callback, args ) { + var ret, name, + old = {}; + + // Remember the old values, and insert the new ones + for ( name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + ret = callback.apply( elem, args || [] ); + + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } + + return ret; +}; + + +var documentElement = document.documentElement; + + + +( function() { + var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, reliableMarginLeftVal, + container = document.createElement( "div" ), + div = document.createElement( "div" ); + + // Finish early in limited (non-browser) environments + if ( !div.style ) { + return; + } + + // Support: IE9-11+ + // Style of cloned element affects source element cloned (#8908) + div.style.backgroundClip = "content-box"; + div.cloneNode( true ).style.backgroundClip = ""; + support.clearCloneStyle = div.style.backgroundClip === "content-box"; + + container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" + + "padding:0;margin-top:1px;position:absolute"; + container.appendChild( div ); + + // Executing both pixelPosition & boxSizingReliable tests require only one layout + // so they're executed at the same time to save the second computation. + function computeStyleTests() { + div.style.cssText = + + // Support: Firefox<29, Android 2.3 + // Vendor-prefix box-sizing + "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;" + + "position:relative;display:block;" + + "margin:auto;border:1px;padding:1px;" + + "top:1%;width:50%"; + div.innerHTML = ""; + documentElement.appendChild( container ); + + var divStyle = window.getComputedStyle( div ); + pixelPositionVal = divStyle.top !== "1%"; + reliableMarginLeftVal = divStyle.marginLeft === "2px"; + boxSizingReliableVal = divStyle.width === "4px"; + + // Support: Android 4.0 - 4.3 only + // Some styles come back with percentage values, even though they shouldn't + div.style.marginRight = "50%"; + pixelMarginRightVal = divStyle.marginRight === "4px"; + + documentElement.removeChild( container ); + } + + jQuery.extend( support, { + pixelPosition: function() { + + // This test is executed only once but we still do memoizing + // since we can use the boxSizingReliable pre-computing. + // No need to check if the test was already performed, though. + computeStyleTests(); + return pixelPositionVal; + }, + boxSizingReliable: function() { + if ( boxSizingReliableVal == null ) { + computeStyleTests(); + } + return boxSizingReliableVal; + }, + pixelMarginRight: function() { + + // Support: Android 4.0-4.3 + // We're checking for boxSizingReliableVal here instead of pixelMarginRightVal + // since that compresses better and they're computed together anyway. + if ( boxSizingReliableVal == null ) { + computeStyleTests(); + } + return pixelMarginRightVal; + }, + reliableMarginLeft: function() { + + // Support: IE <=8 only, Android 4.0 - 4.3 only, Firefox <=3 - 37 + if ( boxSizingReliableVal == null ) { + computeStyleTests(); + } + return reliableMarginLeftVal; + }, + reliableMarginRight: function() { + + // Support: Android 2.3 + // Check if div with explicit width and no margin-right incorrectly + // gets computed margin-right based on width of container. (#3333) + // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right + // This support function is only executed once so no memoizing is needed. + var ret, + marginDiv = div.appendChild( document.createElement( "div" ) ); + + // Reset CSS: box-sizing; display; margin; border; padding + marginDiv.style.cssText = div.style.cssText = + + // Support: Android 2.3 + // Vendor-prefix box-sizing + "-webkit-box-sizing:content-box;box-sizing:content-box;" + + "display:block;margin:0;border:0;padding:0"; + marginDiv.style.marginRight = marginDiv.style.width = "0"; + div.style.width = "1px"; + documentElement.appendChild( container ); + + ret = !parseFloat( window.getComputedStyle( marginDiv ).marginRight ); + + documentElement.removeChild( container ); + div.removeChild( marginDiv ); + + return ret; + } + } ); +} )(); + + +function curCSS( elem, name, computed ) { + var width, minWidth, maxWidth, ret, + style = elem.style; + + computed = computed || getStyles( elem ); + + // Support: IE9 + // getPropertyValue is only needed for .css('filter') (#12537) + if ( computed ) { + ret = computed.getPropertyValue( name ) || computed[ name ]; + + if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { + ret = jQuery.style( elem, name ); + } + + // A tribute to the "awesome hack by Dean Edwards" + // Android Browser returns percentage for some values, + // but width seems to be reliably pixels. + // This is against the CSSOM draft spec: + // http://dev.w3.org/csswg/cssom/#resolved-values + if ( !support.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.test( name ) ) { + + // Remember the original values + width = style.width; + minWidth = style.minWidth; + maxWidth = style.maxWidth; + + // Put in the new values to get a computed value out + style.minWidth = style.maxWidth = style.width = ret; + ret = computed.width; + + // Revert the changed values + style.width = width; + style.minWidth = minWidth; + style.maxWidth = maxWidth; + } + } + + return ret !== undefined ? + + // Support: IE9-11+ + // IE returns zIndex value as an integer. + ret + "" : + ret; +} + + +function addGetHookIf( conditionFn, hookFn ) { + + // Define the hook, we'll check on the first run if it's really needed. + return { + get: function() { + if ( conditionFn() ) { + + // Hook not needed (or it's not possible to use it due + // to missing dependency), remove it. + delete this.get; + return; + } + + // Hook needed; redefine it so that the support test is not executed again. + return ( this.get = hookFn ).apply( this, arguments ); + } + }; +} + + +var + + // Swappable if display is none or starts with table + // except "table", "table-cell", or "table-caption" + // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display + rdisplayswap = /^(none|table(?!-c[ea]).+)/, + + cssShow = { position: "absolute", visibility: "hidden", display: "block" }, + cssNormalTransform = { + letterSpacing: "0", + fontWeight: "400" + }, + + cssPrefixes = [ "Webkit", "O", "Moz", "ms" ], + emptyStyle = document.createElement( "div" ).style; + +// Return a css property mapped to a potentially vendor prefixed property +function vendorPropName( name ) { + + // Shortcut for names that are not vendor prefixed + if ( name in emptyStyle ) { + return name; + } + + // Check for vendor prefixed names + var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), + i = cssPrefixes.length; + + while ( i-- ) { + name = cssPrefixes[ i ] + capName; + if ( name in emptyStyle ) { + return name; + } + } +} + +function setPositiveNumber( elem, value, subtract ) { + + // Any relative (+/-) values have already been + // normalized at this point + var matches = rcssNum.exec( value ); + return matches ? + + // Guard against undefined "subtract", e.g., when used as in cssHooks + Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : + value; +} + +function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { + var i = extra === ( isBorderBox ? "border" : "content" ) ? + + // If we already have the right measurement, avoid augmentation + 4 : + + // Otherwise initialize for horizontal or vertical properties + name === "width" ? 1 : 0, + + val = 0; + + for ( ; i < 4; i += 2 ) { + + // Both box models exclude margin, so add it if we want it + if ( extra === "margin" ) { + val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); + } + + if ( isBorderBox ) { + + // border-box includes padding, so remove it if we want content + if ( extra === "content" ) { + val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + } + + // At this point, extra isn't border nor margin, so remove border + if ( extra !== "margin" ) { + val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } else { + + // At this point, extra isn't content, so add padding + val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + + // At this point, extra isn't content nor padding, so add border + if ( extra !== "padding" ) { + val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } + } + + return val; +} + +function getWidthOrHeight( elem, name, extra ) { + + // Start with offset property, which is equivalent to the border-box value + var valueIsBorderBox = true, + val = name === "width" ? elem.offsetWidth : elem.offsetHeight, + styles = getStyles( elem ), + isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; + + // Support: IE11 only + // In IE 11 fullscreen elements inside of an iframe have + // 100x too small dimensions (gh-1764). + if ( document.msFullscreenElement && window.top !== window ) { + + // Support: IE11 only + // Running getBoundingClientRect on a disconnected node + // in IE throws an error. + if ( elem.getClientRects().length ) { + val = Math.round( elem.getBoundingClientRect()[ name ] * 100 ); + } + } + + // Some non-html elements return undefined for offsetWidth, so check for null/undefined + // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 + // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 + if ( val <= 0 || val == null ) { + + // Fall back to computed then uncomputed css if necessary + val = curCSS( elem, name, styles ); + if ( val < 0 || val == null ) { + val = elem.style[ name ]; + } + + // Computed unit is not pixels. Stop here and return. + if ( rnumnonpx.test( val ) ) { + return val; + } + + // Check for style in case a browser which returns unreliable values + // for getComputedStyle silently falls back to the reliable elem.style + valueIsBorderBox = isBorderBox && + ( support.boxSizingReliable() || val === elem.style[ name ] ); + + // Normalize "", auto, and prepare for extra + val = parseFloat( val ) || 0; + } + + // Use the active box-sizing model to add/subtract irrelevant styles + return ( val + + augmentWidthOrHeight( + elem, + name, + extra || ( isBorderBox ? "border" : "content" ), + valueIsBorderBox, + styles + ) + ) + "px"; +} + +function showHide( elements, show ) { + var display, elem, hidden, + values = [], + index = 0, + length = elements.length; + + for ( ; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + + values[ index ] = dataPriv.get( elem, "olddisplay" ); + display = elem.style.display; + if ( show ) { + + // Reset the inline display of this element to learn if it is + // being hidden by cascaded rules or not + if ( !values[ index ] && display === "none" ) { + elem.style.display = ""; + } + + // Set elements which have been overridden with display: none + // in a stylesheet to whatever the default browser style is + // for such an element + if ( elem.style.display === "" && isHidden( elem ) ) { + values[ index ] = dataPriv.access( + elem, + "olddisplay", + defaultDisplay( elem.nodeName ) + ); + } + } else { + hidden = isHidden( elem ); + + if ( display !== "none" || !hidden ) { + dataPriv.set( + elem, + "olddisplay", + hidden ? display : jQuery.css( elem, "display" ) + ); + } + } + } + + // Set the display of most of the elements in a second loop + // to avoid the constant reflow + for ( index = 0; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + if ( !show || elem.style.display === "none" || elem.style.display === "" ) { + elem.style.display = show ? values[ index ] || "" : "none"; + } + } + + return elements; +} + +jQuery.extend( { + + // Add in style property hooks for overriding the default + // behavior of getting and setting a style property + cssHooks: { + opacity: { + get: function( elem, computed ) { + if ( computed ) { + + // We should always get a number back from opacity + var ret = curCSS( elem, "opacity" ); + return ret === "" ? "1" : ret; + } + } + } + }, + + // Don't automatically add "px" to these possibly-unitless properties + cssNumber: { + "animationIterationCount": true, + "columnCount": true, + "fillOpacity": true, + "flexGrow": true, + "flexShrink": true, + "fontWeight": true, + "lineHeight": true, + "opacity": true, + "order": true, + "orphans": true, + "widows": true, + "zIndex": true, + "zoom": true + }, + + // Add in properties whose names you wish to fix before + // setting or getting the value + cssProps: { + "float": "cssFloat" + }, + + // Get and set the style property on a DOM Node + style: function( elem, name, value, extra ) { + + // Don't set styles on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { + return; + } + + // Make sure that we're working with the right name + var ret, type, hooks, + origName = jQuery.camelCase( name ), + style = elem.style; + + name = jQuery.cssProps[ origName ] || + ( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName ); + + // Gets hook for the prefixed version, then unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // Check if we're setting a value + if ( value !== undefined ) { + type = typeof value; + + // Convert "+=" or "-=" to relative numbers (#7345) + if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { + value = adjustCSS( elem, name, ret ); + + // Fixes bug #9237 + type = "number"; + } + + // Make sure that null and NaN values aren't set (#7116) + if ( value == null || value !== value ) { + return; + } + + // If a number was passed in, add the unit (except for certain CSS properties) + if ( type === "number" ) { + value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); + } + + // Support: IE9-11+ + // background-* props affect original clone's values + if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { + style[ name ] = "inherit"; + } + + // If a hook was provided, use that value, otherwise just set the specified value + if ( !hooks || !( "set" in hooks ) || + ( value = hooks.set( elem, value, extra ) ) !== undefined ) { + + style[ name ] = value; + } + + } else { + + // If a hook was provided get the non-computed value from there + if ( hooks && "get" in hooks && + ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { + + return ret; + } + + // Otherwise just get the value from the style object + return style[ name ]; + } + }, + + css: function( elem, name, extra, styles ) { + var val, num, hooks, + origName = jQuery.camelCase( name ); + + // Make sure that we're working with the right name + name = jQuery.cssProps[ origName ] || + ( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName ); + + // Try prefixed name followed by the unprefixed name + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // If a hook was provided get the computed value from there + if ( hooks && "get" in hooks ) { + val = hooks.get( elem, true, extra ); + } + + // Otherwise, if a way to get the computed value exists, use that + if ( val === undefined ) { + val = curCSS( elem, name, styles ); + } + + // Convert "normal" to computed value + if ( val === "normal" && name in cssNormalTransform ) { + val = cssNormalTransform[ name ]; + } + + // Make numeric if forced or a qualifier was provided and val looks numeric + if ( extra === "" || extra ) { + num = parseFloat( val ); + return extra === true || isFinite( num ) ? num || 0 : val; + } + return val; + } +} ); + +jQuery.each( [ "height", "width" ], function( i, name ) { + jQuery.cssHooks[ name ] = { + get: function( elem, computed, extra ) { + if ( computed ) { + + // Certain elements can have dimension info if we invisibly show them + // but it must have a current display style that would benefit + return rdisplayswap.test( jQuery.css( elem, "display" ) ) && + elem.offsetWidth === 0 ? + swap( elem, cssShow, function() { + return getWidthOrHeight( elem, name, extra ); + } ) : + getWidthOrHeight( elem, name, extra ); + } + }, + + set: function( elem, value, extra ) { + var matches, + styles = extra && getStyles( elem ), + subtract = extra && augmentWidthOrHeight( + elem, + name, + extra, + jQuery.css( elem, "boxSizing", false, styles ) === "border-box", + styles + ); + + // Convert to pixels if value adjustment is needed + if ( subtract && ( matches = rcssNum.exec( value ) ) && + ( matches[ 3 ] || "px" ) !== "px" ) { + + elem.style[ name ] = value; + value = jQuery.css( elem, name ); + } + + return setPositiveNumber( elem, value, subtract ); + } + }; +} ); + +jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, + function( elem, computed ) { + if ( computed ) { + return ( parseFloat( curCSS( elem, "marginLeft" ) ) || + elem.getBoundingClientRect().left - + swap( elem, { marginLeft: 0 }, function() { + return elem.getBoundingClientRect().left; + } ) + ) + "px"; + } + } +); + +// Support: Android 2.3 +jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight, + function( elem, computed ) { + if ( computed ) { + return swap( elem, { "display": "inline-block" }, + curCSS, [ elem, "marginRight" ] ); + } + } +); + +// These hooks are used by animate to expand properties +jQuery.each( { + margin: "", + padding: "", + border: "Width" +}, function( prefix, suffix ) { + jQuery.cssHooks[ prefix + suffix ] = { + expand: function( value ) { + var i = 0, + expanded = {}, + + // Assumes a single number if not a string + parts = typeof value === "string" ? value.split( " " ) : [ value ]; + + for ( ; i < 4; i++ ) { + expanded[ prefix + cssExpand[ i ] + suffix ] = + parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; + } + + return expanded; + } + }; + + if ( !rmargin.test( prefix ) ) { + jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; + } +} ); + +jQuery.fn.extend( { + css: function( name, value ) { + return access( this, function( elem, name, value ) { + var styles, len, + map = {}, + i = 0; + + if ( jQuery.isArray( name ) ) { + styles = getStyles( elem ); + len = name.length; + + for ( ; i < len; i++ ) { + map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); + } + + return map; + } + + return value !== undefined ? + jQuery.style( elem, name, value ) : + jQuery.css( elem, name ); + }, name, value, arguments.length > 1 ); + }, + show: function() { + return showHide( this, true ); + }, + hide: function() { + return showHide( this ); + }, + toggle: function( state ) { + if ( typeof state === "boolean" ) { + return state ? this.show() : this.hide(); + } + + return this.each( function() { + if ( isHidden( this ) ) { + jQuery( this ).show(); + } else { + jQuery( this ).hide(); + } + } ); + } +} ); + + +function Tween( elem, options, prop, end, easing ) { + return new Tween.prototype.init( elem, options, prop, end, easing ); +} +jQuery.Tween = Tween; + +Tween.prototype = { + constructor: Tween, + init: function( elem, options, prop, end, easing, unit ) { + this.elem = elem; + this.prop = prop; + this.easing = easing || jQuery.easing._default; + this.options = options; + this.start = this.now = this.cur(); + this.end = end; + this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); + }, + cur: function() { + var hooks = Tween.propHooks[ this.prop ]; + + return hooks && hooks.get ? + hooks.get( this ) : + Tween.propHooks._default.get( this ); + }, + run: function( percent ) { + var eased, + hooks = Tween.propHooks[ this.prop ]; + + if ( this.options.duration ) { + this.pos = eased = jQuery.easing[ this.easing ]( + percent, this.options.duration * percent, 0, 1, this.options.duration + ); + } else { + this.pos = eased = percent; + } + this.now = ( this.end - this.start ) * eased + this.start; + + if ( this.options.step ) { + this.options.step.call( this.elem, this.now, this ); + } + + if ( hooks && hooks.set ) { + hooks.set( this ); + } else { + Tween.propHooks._default.set( this ); + } + return this; + } +}; + +Tween.prototype.init.prototype = Tween.prototype; + +Tween.propHooks = { + _default: { + get: function( tween ) { + var result; + + // Use a property on the element directly when it is not a DOM element, + // or when there is no matching style property that exists. + if ( tween.elem.nodeType !== 1 || + tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { + return tween.elem[ tween.prop ]; + } + + // Passing an empty string as a 3rd parameter to .css will automatically + // attempt a parseFloat and fallback to a string if the parse fails. + // Simple values such as "10px" are parsed to Float; + // complex values such as "rotate(1rad)" are returned as-is. + result = jQuery.css( tween.elem, tween.prop, "" ); + + // Empty strings, null, undefined and "auto" are converted to 0. + return !result || result === "auto" ? 0 : result; + }, + set: function( tween ) { + + // Use step hook for back compat. + // Use cssHook if its there. + // Use .style if available and use plain properties where available. + if ( jQuery.fx.step[ tween.prop ] ) { + jQuery.fx.step[ tween.prop ]( tween ); + } else if ( tween.elem.nodeType === 1 && + ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || + jQuery.cssHooks[ tween.prop ] ) ) { + jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); + } else { + tween.elem[ tween.prop ] = tween.now; + } + } + } +}; + +// Support: IE9 +// Panic based approach to setting things on disconnected nodes +Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { + set: function( tween ) { + if ( tween.elem.nodeType && tween.elem.parentNode ) { + tween.elem[ tween.prop ] = tween.now; + } + } +}; + +jQuery.easing = { + linear: function( p ) { + return p; + }, + swing: function( p ) { + return 0.5 - Math.cos( p * Math.PI ) / 2; + }, + _default: "swing" +}; + +jQuery.fx = Tween.prototype.init; + +// Back Compat <1.8 extension point +jQuery.fx.step = {}; + + + + +var + fxNow, timerId, + rfxtypes = /^(?:toggle|show|hide)$/, + rrun = /queueHooks$/; + +// Animations created synchronously will run synchronously +function createFxNow() { + window.setTimeout( function() { + fxNow = undefined; + } ); + return ( fxNow = jQuery.now() ); +} + +// Generate parameters to create a standard animation +function genFx( type, includeWidth ) { + var which, + i = 0, + attrs = { height: type }; + + // If we include width, step value is 1 to do all cssExpand values, + // otherwise step value is 2 to skip over Left and Right + includeWidth = includeWidth ? 1 : 0; + for ( ; i < 4 ; i += 2 - includeWidth ) { + which = cssExpand[ i ]; + attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; + } + + if ( includeWidth ) { + attrs.opacity = attrs.width = type; + } + + return attrs; +} + +function createTween( value, prop, animation ) { + var tween, + collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), + index = 0, + length = collection.length; + for ( ; index < length; index++ ) { + if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { + + // We're done with this property + return tween; + } + } +} + +function defaultPrefilter( elem, props, opts ) { + /* jshint validthis: true */ + var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay, + anim = this, + orig = {}, + style = elem.style, + hidden = elem.nodeType && isHidden( elem ), + dataShow = dataPriv.get( elem, "fxshow" ); + + // Handle queue: false promises + if ( !opts.queue ) { + hooks = jQuery._queueHooks( elem, "fx" ); + if ( hooks.unqueued == null ) { + hooks.unqueued = 0; + oldfire = hooks.empty.fire; + hooks.empty.fire = function() { + if ( !hooks.unqueued ) { + oldfire(); + } + }; + } + hooks.unqueued++; + + anim.always( function() { + + // Ensure the complete handler is called before this completes + anim.always( function() { + hooks.unqueued--; + if ( !jQuery.queue( elem, "fx" ).length ) { + hooks.empty.fire(); + } + } ); + } ); + } + + // Height/width overflow pass + if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { + + // Make sure that nothing sneaks out + // Record all 3 overflow attributes because IE9-10 do not + // change the overflow attribute when overflowX and + // overflowY are set to the same value + opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; + + // Set display property to inline-block for height/width + // animations on inline elements that are having width/height animated + display = jQuery.css( elem, "display" ); + + // Test default display if display is currently "none" + checkDisplay = display === "none" ? + dataPriv.get( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display; + + if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) { + style.display = "inline-block"; + } + } + + if ( opts.overflow ) { + style.overflow = "hidden"; + anim.always( function() { + style.overflow = opts.overflow[ 0 ]; + style.overflowX = opts.overflow[ 1 ]; + style.overflowY = opts.overflow[ 2 ]; + } ); + } + + // show/hide pass + for ( prop in props ) { + value = props[ prop ]; + if ( rfxtypes.exec( value ) ) { + delete props[ prop ]; + toggle = toggle || value === "toggle"; + if ( value === ( hidden ? "hide" : "show" ) ) { + + // If there is dataShow left over from a stopped hide or show + // and we are going to proceed with show, we should pretend to be hidden + if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { + hidden = true; + } else { + continue; + } + } + orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); + + // Any non-fx value stops us from restoring the original display value + } else { + display = undefined; + } + } + + if ( !jQuery.isEmptyObject( orig ) ) { + if ( dataShow ) { + if ( "hidden" in dataShow ) { + hidden = dataShow.hidden; + } + } else { + dataShow = dataPriv.access( elem, "fxshow", {} ); + } + + // Store state if its toggle - enables .stop().toggle() to "reverse" + if ( toggle ) { + dataShow.hidden = !hidden; + } + if ( hidden ) { + jQuery( elem ).show(); + } else { + anim.done( function() { + jQuery( elem ).hide(); + } ); + } + anim.done( function() { + var prop; + + dataPriv.remove( elem, "fxshow" ); + for ( prop in orig ) { + jQuery.style( elem, prop, orig[ prop ] ); + } + } ); + for ( prop in orig ) { + tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); + + if ( !( prop in dataShow ) ) { + dataShow[ prop ] = tween.start; + if ( hidden ) { + tween.end = tween.start; + tween.start = prop === "width" || prop === "height" ? 1 : 0; + } + } + } + + // If this is a noop like .hide().hide(), restore an overwritten display value + } else if ( ( display === "none" ? defaultDisplay( elem.nodeName ) : display ) === "inline" ) { + style.display = display; + } +} + +function propFilter( props, specialEasing ) { + var index, name, easing, value, hooks; + + // camelCase, specialEasing and expand cssHook pass + for ( index in props ) { + name = jQuery.camelCase( index ); + easing = specialEasing[ name ]; + value = props[ index ]; + if ( jQuery.isArray( value ) ) { + easing = value[ 1 ]; + value = props[ index ] = value[ 0 ]; + } + + if ( index !== name ) { + props[ name ] = value; + delete props[ index ]; + } + + hooks = jQuery.cssHooks[ name ]; + if ( hooks && "expand" in hooks ) { + value = hooks.expand( value ); + delete props[ name ]; + + // Not quite $.extend, this won't overwrite existing keys. + // Reusing 'index' because we have the correct "name" + for ( index in value ) { + if ( !( index in props ) ) { + props[ index ] = value[ index ]; + specialEasing[ index ] = easing; + } + } + } else { + specialEasing[ name ] = easing; + } + } +} + +function Animation( elem, properties, options ) { + var result, + stopped, + index = 0, + length = Animation.prefilters.length, + deferred = jQuery.Deferred().always( function() { + + // Don't match elem in the :animated selector + delete tick.elem; + } ), + tick = function() { + if ( stopped ) { + return false; + } + var currentTime = fxNow || createFxNow(), + remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), + + // Support: Android 2.3 + // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) + temp = remaining / animation.duration || 0, + percent = 1 - temp, + index = 0, + length = animation.tweens.length; + + for ( ; index < length ; index++ ) { + animation.tweens[ index ].run( percent ); + } + + deferred.notifyWith( elem, [ animation, percent, remaining ] ); + + if ( percent < 1 && length ) { + return remaining; + } else { + deferred.resolveWith( elem, [ animation ] ); + return false; + } + }, + animation = deferred.promise( { + elem: elem, + props: jQuery.extend( {}, properties ), + opts: jQuery.extend( true, { + specialEasing: {}, + easing: jQuery.easing._default + }, options ), + originalProperties: properties, + originalOptions: options, + startTime: fxNow || createFxNow(), + duration: options.duration, + tweens: [], + createTween: function( prop, end ) { + var tween = jQuery.Tween( elem, animation.opts, prop, end, + animation.opts.specialEasing[ prop ] || animation.opts.easing ); + animation.tweens.push( tween ); + return tween; + }, + stop: function( gotoEnd ) { + var index = 0, + + // If we are going to the end, we want to run all the tweens + // otherwise we skip this part + length = gotoEnd ? animation.tweens.length : 0; + if ( stopped ) { + return this; + } + stopped = true; + for ( ; index < length ; index++ ) { + animation.tweens[ index ].run( 1 ); + } + + // Resolve when we played the last frame; otherwise, reject + if ( gotoEnd ) { + deferred.notifyWith( elem, [ animation, 1, 0 ] ); + deferred.resolveWith( elem, [ animation, gotoEnd ] ); + } else { + deferred.rejectWith( elem, [ animation, gotoEnd ] ); + } + return this; + } + } ), + props = animation.props; + + propFilter( props, animation.opts.specialEasing ); + + for ( ; index < length ; index++ ) { + result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); + if ( result ) { + if ( jQuery.isFunction( result.stop ) ) { + jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = + jQuery.proxy( result.stop, result ); + } + return result; + } + } + + jQuery.map( props, createTween, animation ); + + if ( jQuery.isFunction( animation.opts.start ) ) { + animation.opts.start.call( elem, animation ); + } + + jQuery.fx.timer( + jQuery.extend( tick, { + elem: elem, + anim: animation, + queue: animation.opts.queue + } ) + ); + + // attach callbacks from options + return animation.progress( animation.opts.progress ) + .done( animation.opts.done, animation.opts.complete ) + .fail( animation.opts.fail ) + .always( animation.opts.always ); +} + +jQuery.Animation = jQuery.extend( Animation, { + tweeners: { + "*": [ function( prop, value ) { + var tween = this.createTween( prop, value ); + adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); + return tween; + } ] + }, + + tweener: function( props, callback ) { + if ( jQuery.isFunction( props ) ) { + callback = props; + props = [ "*" ]; + } else { + props = props.match( rnotwhite ); + } + + var prop, + index = 0, + length = props.length; + + for ( ; index < length ; index++ ) { + prop = props[ index ]; + Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; + Animation.tweeners[ prop ].unshift( callback ); + } + }, + + prefilters: [ defaultPrefilter ], + + prefilter: function( callback, prepend ) { + if ( prepend ) { + Animation.prefilters.unshift( callback ); + } else { + Animation.prefilters.push( callback ); + } + } +} ); + +jQuery.speed = function( speed, easing, fn ) { + var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { + complete: fn || !fn && easing || + jQuery.isFunction( speed ) && speed, + duration: speed, + easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing + }; + + opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? + opt.duration : opt.duration in jQuery.fx.speeds ? + jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; + + // Normalize opt.queue - true/undefined/null -> "fx" + if ( opt.queue == null || opt.queue === true ) { + opt.queue = "fx"; + } + + // Queueing + opt.old = opt.complete; + + opt.complete = function() { + if ( jQuery.isFunction( opt.old ) ) { + opt.old.call( this ); + } + + if ( opt.queue ) { + jQuery.dequeue( this, opt.queue ); + } + }; + + return opt; +}; + +jQuery.fn.extend( { + fadeTo: function( speed, to, easing, callback ) { + + // Show any hidden elements after setting opacity to 0 + return this.filter( isHidden ).css( "opacity", 0 ).show() + + // Animate to the value specified + .end().animate( { opacity: to }, speed, easing, callback ); + }, + animate: function( prop, speed, easing, callback ) { + var empty = jQuery.isEmptyObject( prop ), + optall = jQuery.speed( speed, easing, callback ), + doAnimation = function() { + + // Operate on a copy of prop so per-property easing won't be lost + var anim = Animation( this, jQuery.extend( {}, prop ), optall ); + + // Empty animations, or finishing resolves immediately + if ( empty || dataPriv.get( this, "finish" ) ) { + anim.stop( true ); + } + }; + doAnimation.finish = doAnimation; + + return empty || optall.queue === false ? + this.each( doAnimation ) : + this.queue( optall.queue, doAnimation ); + }, + stop: function( type, clearQueue, gotoEnd ) { + var stopQueue = function( hooks ) { + var stop = hooks.stop; + delete hooks.stop; + stop( gotoEnd ); + }; + + if ( typeof type !== "string" ) { + gotoEnd = clearQueue; + clearQueue = type; + type = undefined; + } + if ( clearQueue && type !== false ) { + this.queue( type || "fx", [] ); + } + + return this.each( function() { + var dequeue = true, + index = type != null && type + "queueHooks", + timers = jQuery.timers, + data = dataPriv.get( this ); + + if ( index ) { + if ( data[ index ] && data[ index ].stop ) { + stopQueue( data[ index ] ); + } + } else { + for ( index in data ) { + if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { + stopQueue( data[ index ] ); + } + } + } + + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && + ( type == null || timers[ index ].queue === type ) ) { + + timers[ index ].anim.stop( gotoEnd ); + dequeue = false; + timers.splice( index, 1 ); + } + } + + // Start the next in the queue if the last step wasn't forced. + // Timers currently will call their complete callbacks, which + // will dequeue but only if they were gotoEnd. + if ( dequeue || !gotoEnd ) { + jQuery.dequeue( this, type ); + } + } ); + }, + finish: function( type ) { + if ( type !== false ) { + type = type || "fx"; + } + return this.each( function() { + var index, + data = dataPriv.get( this ), + queue = data[ type + "queue" ], + hooks = data[ type + "queueHooks" ], + timers = jQuery.timers, + length = queue ? queue.length : 0; + + // Enable finishing flag on private data + data.finish = true; + + // Empty the queue first + jQuery.queue( this, type, [] ); + + if ( hooks && hooks.stop ) { + hooks.stop.call( this, true ); + } + + // Look for any active animations, and finish them + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && timers[ index ].queue === type ) { + timers[ index ].anim.stop( true ); + timers.splice( index, 1 ); + } + } + + // Look for any animations in the old queue and finish them + for ( index = 0; index < length; index++ ) { + if ( queue[ index ] && queue[ index ].finish ) { + queue[ index ].finish.call( this ); + } + } + + // Turn off finishing flag + delete data.finish; + } ); + } +} ); + +jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) { + var cssFn = jQuery.fn[ name ]; + jQuery.fn[ name ] = function( speed, easing, callback ) { + return speed == null || typeof speed === "boolean" ? + cssFn.apply( this, arguments ) : + this.animate( genFx( name, true ), speed, easing, callback ); + }; +} ); + +// Generate shortcuts for custom animations +jQuery.each( { + slideDown: genFx( "show" ), + slideUp: genFx( "hide" ), + slideToggle: genFx( "toggle" ), + fadeIn: { opacity: "show" }, + fadeOut: { opacity: "hide" }, + fadeToggle: { opacity: "toggle" } +}, function( name, props ) { + jQuery.fn[ name ] = function( speed, easing, callback ) { + return this.animate( props, speed, easing, callback ); + }; +} ); + +jQuery.timers = []; +jQuery.fx.tick = function() { + var timer, + i = 0, + timers = jQuery.timers; + + fxNow = jQuery.now(); + + for ( ; i < timers.length; i++ ) { + timer = timers[ i ]; + + // Checks the timer has not already been removed + if ( !timer() && timers[ i ] === timer ) { + timers.splice( i--, 1 ); + } + } + + if ( !timers.length ) { + jQuery.fx.stop(); + } + fxNow = undefined; +}; + +jQuery.fx.timer = function( timer ) { + jQuery.timers.push( timer ); + if ( timer() ) { + jQuery.fx.start(); + } else { + jQuery.timers.pop(); + } +}; + +jQuery.fx.interval = 13; +jQuery.fx.start = function() { + if ( !timerId ) { + timerId = window.setInterval( jQuery.fx.tick, jQuery.fx.interval ); + } +}; + +jQuery.fx.stop = function() { + window.clearInterval( timerId ); + + timerId = null; +}; + +jQuery.fx.speeds = { + slow: 600, + fast: 200, + + // Default speed + _default: 400 +}; + + +// Based off of the plugin by Clint Helfers, with permission. +// http://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ +jQuery.fn.delay = function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = window.setTimeout( next, time ); + hooks.stop = function() { + window.clearTimeout( timeout ); + }; + } ); +}; + + +( function() { + var input = document.createElement( "input" ), + select = document.createElement( "select" ), + opt = select.appendChild( document.createElement( "option" ) ); + + input.type = "checkbox"; + + // Support: iOS<=5.1, Android<=4.2+ + // Default value for a checkbox should be "on" + support.checkOn = input.value !== ""; + + // Support: IE<=11+ + // Must access selectedIndex to make default options select + support.optSelected = opt.selected; + + // Support: Android<=2.3 + // Options inside disabled selects are incorrectly marked as disabled + select.disabled = true; + support.optDisabled = !opt.disabled; + + // Support: IE<=11+ + // An input loses its value after becoming a radio + input = document.createElement( "input" ); + input.value = "t"; + input.type = "radio"; + support.radioValue = input.value === "t"; +} )(); + + +var boolHook, + attrHandle = jQuery.expr.attrHandle; + +jQuery.fn.extend( { + attr: function( name, value ) { + return access( this, jQuery.attr, name, value, arguments.length > 1 ); + }, + + removeAttr: function( name ) { + return this.each( function() { + jQuery.removeAttr( this, name ); + } ); + } +} ); + +jQuery.extend( { + attr: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set attributes on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === "undefined" ) { + return jQuery.prop( elem, name, value ); + } + + // All attributes are lowercase + // Grab necessary hook if one is defined + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + name = name.toLowerCase(); + hooks = jQuery.attrHooks[ name ] || + ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); + } + + if ( value !== undefined ) { + if ( value === null ) { + jQuery.removeAttr( elem, name ); + return; + } + + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + elem.setAttribute( name, value + "" ); + return value; + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + ret = jQuery.find.attr( elem, name ); + + // Non-existent attributes return null, we normalize to undefined + return ret == null ? undefined : ret; + }, + + attrHooks: { + type: { + set: function( elem, value ) { + if ( !support.radioValue && value === "radio" && + jQuery.nodeName( elem, "input" ) ) { + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + } + }, + + removeAttr: function( elem, value ) { + var name, propName, + i = 0, + attrNames = value && value.match( rnotwhite ); + + if ( attrNames && elem.nodeType === 1 ) { + while ( ( name = attrNames[ i++ ] ) ) { + propName = jQuery.propFix[ name ] || name; + + // Boolean attributes get special treatment (#10870) + if ( jQuery.expr.match.bool.test( name ) ) { + + // Set corresponding property to false + elem[ propName ] = false; + } + + elem.removeAttribute( name ); + } + } + } +} ); + +// Hooks for boolean attributes +boolHook = { + set: function( elem, value, name ) { + if ( value === false ) { + + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + elem.setAttribute( name, name ); + } + return name; + } +}; +jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { + var getter = attrHandle[ name ] || jQuery.find.attr; + + attrHandle[ name ] = function( elem, name, isXML ) { + var ret, handle; + if ( !isXML ) { + + // Avoid an infinite loop by temporarily removing this function from the getter + handle = attrHandle[ name ]; + attrHandle[ name ] = ret; + ret = getter( elem, name, isXML ) != null ? + name.toLowerCase() : + null; + attrHandle[ name ] = handle; + } + return ret; + }; +} ); + + + + +var rfocusable = /^(?:input|select|textarea|button)$/i, + rclickable = /^(?:a|area)$/i; + +jQuery.fn.extend( { + prop: function( name, value ) { + return access( this, jQuery.prop, name, value, arguments.length > 1 ); + }, + + removeProp: function( name ) { + return this.each( function() { + delete this[ jQuery.propFix[ name ] || name ]; + } ); + } +} ); + +jQuery.extend( { + prop: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set properties on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + return ( elem[ name ] = value ); + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + return elem[ name ]; + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + + // elem.tabIndex doesn't always return the + // correct value when it hasn't been explicitly set + // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + // Use proper attribute retrieval(#12072) + var tabindex = jQuery.find.attr( elem, "tabindex" ); + + return tabindex ? + parseInt( tabindex, 10 ) : + rfocusable.test( elem.nodeName ) || + rclickable.test( elem.nodeName ) && elem.href ? + 0 : + -1; + } + } + }, + + propFix: { + "for": "htmlFor", + "class": "className" + } +} ); + +if ( !support.optSelected ) { + jQuery.propHooks.selected = { + get: function( elem ) { + var parent = elem.parentNode; + if ( parent && parent.parentNode ) { + parent.parentNode.selectedIndex; + } + return null; + } + }; +} + +jQuery.each( [ + "tabIndex", + "readOnly", + "maxLength", + "cellSpacing", + "cellPadding", + "rowSpan", + "colSpan", + "useMap", + "frameBorder", + "contentEditable" +], function() { + jQuery.propFix[ this.toLowerCase() ] = this; +} ); + + + + +var rclass = /[\t\r\n\f]/g; + +function getClass( elem ) { + return elem.getAttribute && elem.getAttribute( "class" ) || ""; +} + +jQuery.fn.extend( { + addClass: function( value ) { + var classes, elem, cur, curValue, clazz, j, finalValue, + i = 0; + + if ( jQuery.isFunction( value ) ) { + return this.each( function( j ) { + jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + if ( typeof value === "string" && value ) { + classes = value.match( rnotwhite ) || []; + + while ( ( elem = this[ i++ ] ) ) { + curValue = getClass( elem ); + cur = elem.nodeType === 1 && + ( " " + curValue + " " ).replace( rclass, " " ); + + if ( cur ) { + j = 0; + while ( ( clazz = classes[ j++ ] ) ) { + if ( cur.indexOf( " " + clazz + " " ) < 0 ) { + cur += clazz + " "; + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = jQuery.trim( cur ); + if ( curValue !== finalValue ) { + elem.setAttribute( "class", finalValue ); + } + } + } + } + + return this; + }, + + removeClass: function( value ) { + var classes, elem, cur, curValue, clazz, j, finalValue, + i = 0; + + if ( jQuery.isFunction( value ) ) { + return this.each( function( j ) { + jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + if ( !arguments.length ) { + return this.attr( "class", "" ); + } + + if ( typeof value === "string" && value ) { + classes = value.match( rnotwhite ) || []; + + while ( ( elem = this[ i++ ] ) ) { + curValue = getClass( elem ); + + // This expression is here for better compressibility (see addClass) + cur = elem.nodeType === 1 && + ( " " + curValue + " " ).replace( rclass, " " ); + + if ( cur ) { + j = 0; + while ( ( clazz = classes[ j++ ] ) ) { + + // Remove *all* instances + while ( cur.indexOf( " " + clazz + " " ) > -1 ) { + cur = cur.replace( " " + clazz + " ", " " ); + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = jQuery.trim( cur ); + if ( curValue !== finalValue ) { + elem.setAttribute( "class", finalValue ); + } + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value; + + if ( typeof stateVal === "boolean" && type === "string" ) { + return stateVal ? this.addClass( value ) : this.removeClass( value ); + } + + if ( jQuery.isFunction( value ) ) { + return this.each( function( i ) { + jQuery( this ).toggleClass( + value.call( this, i, getClass( this ), stateVal ), + stateVal + ); + } ); + } + + return this.each( function() { + var className, i, self, classNames; + + if ( type === "string" ) { + + // Toggle individual class names + i = 0; + self = jQuery( this ); + classNames = value.match( rnotwhite ) || []; + + while ( ( className = classNames[ i++ ] ) ) { + + // Check each className given, space separated list + if ( self.hasClass( className ) ) { + self.removeClass( className ); + } else { + self.addClass( className ); + } + } + + // Toggle whole class name + } else if ( value === undefined || type === "boolean" ) { + className = getClass( this ); + if ( className ) { + + // Store className if set + dataPriv.set( this, "__className__", className ); + } + + // If the element has a class name or if we're passed `false`, + // then remove the whole classname (if there was one, the above saved it). + // Otherwise bring back whatever was previously saved (if anything), + // falling back to the empty string if nothing was stored. + if ( this.setAttribute ) { + this.setAttribute( "class", + className || value === false ? + "" : + dataPriv.get( this, "__className__" ) || "" + ); + } + } + } ); + }, + + hasClass: function( selector ) { + var className, elem, + i = 0; + + className = " " + selector + " "; + while ( ( elem = this[ i++ ] ) ) { + if ( elem.nodeType === 1 && + ( " " + getClass( elem ) + " " ).replace( rclass, " " ) + .indexOf( className ) > -1 + ) { + return true; + } + } + + return false; + } +} ); + + + + +var rreturn = /\r/g; + +jQuery.fn.extend( { + val: function( value ) { + var hooks, ret, isFunction, + elem = this[ 0 ]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.type ] || + jQuery.valHooks[ elem.nodeName.toLowerCase() ]; + + if ( hooks && + "get" in hooks && + ( ret = hooks.get( elem, "value" ) ) !== undefined + ) { + return ret; + } + + ret = elem.value; + + return typeof ret === "string" ? + + // Handle most common string cases + ret.replace( rreturn, "" ) : + + // Handle cases where value is null/undef or number + ret == null ? "" : ret; + } + + return; + } + + isFunction = jQuery.isFunction( value ); + + return this.each( function( i ) { + var val; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call( this, i, jQuery( this ).val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + + } else if ( typeof val === "number" ) { + val += ""; + + } else if ( jQuery.isArray( val ) ) { + val = jQuery.map( val, function( value ) { + return value == null ? "" : value + ""; + } ); + } + + hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + } ); + } +} ); + +jQuery.extend( { + valHooks: { + option: { + get: function( elem ) { + + // Support: IE<11 + // option.value not trimmed (#14858) + return jQuery.trim( elem.value ); + } + }, + select: { + get: function( elem ) { + var value, option, + options = elem.options, + index = elem.selectedIndex, + one = elem.type === "select-one" || index < 0, + values = one ? null : [], + max = one ? index + 1 : options.length, + i = index < 0 ? + max : + one ? index : 0; + + // Loop through all the selected options + for ( ; i < max; i++ ) { + option = options[ i ]; + + // IE8-9 doesn't update selected after form reset (#2551) + if ( ( option.selected || i === index ) && + + // Don't return options that are disabled or in a disabled optgroup + ( support.optDisabled ? + !option.disabled : option.getAttribute( "disabled" ) === null ) && + ( !option.parentNode.disabled || + !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + }, + + set: function( elem, value ) { + var optionSet, option, + options = elem.options, + values = jQuery.makeArray( value ), + i = options.length; + + while ( i-- ) { + option = options[ i ]; + if ( option.selected = + jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 + ) { + optionSet = true; + } + } + + // Force browsers to behave consistently when non-matching value is set + if ( !optionSet ) { + elem.selectedIndex = -1; + } + return values; + } + } + } +} ); + +// Radios and checkboxes getter/setter +jQuery.each( [ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + set: function( elem, value ) { + if ( jQuery.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); + } + } + }; + if ( !support.checkOn ) { + jQuery.valHooks[ this ].get = function( elem ) { + return elem.getAttribute( "value" ) === null ? "on" : elem.value; + }; + } +} ); + + + + +// Return jQuery for attributes-only inclusion + + +var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/; + +jQuery.extend( jQuery.event, { + + trigger: function( event, data, elem, onlyHandlers ) { + + var i, cur, tmp, bubbleType, ontype, handle, special, + eventPath = [ elem || document ], + type = hasOwn.call( event, "type" ) ? event.type : event, + namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; + + cur = tmp = elem = elem || document; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf( "." ) > -1 ) { + + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split( "." ); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf( ":" ) < 0 && "on" + type; + + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); + + // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) + event.isTrigger = onlyHandlers ? 2 : 3; + event.namespace = namespaces.join( "." ); + event.rnamespace = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === ( elem.ownerDocument || document ) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); + } + } + + // Fire handlers on the event path + i = 0; + while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { + + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] && + dataPriv.get( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && handle.apply && acceptData( cur ) ) { + event.result = handle.apply( cur, data ); + if ( event.result === false ) { + event.preventDefault(); + } + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( ( !special._default || + special._default.apply( eventPath.pop(), data ) === false ) && + acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name name as the event. + // Don't do default actions on window, that's where global variables be (#6170) + if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + elem[ type ](); + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } + } + } + + return event.result; + }, + + // Piggyback on a donor event to simulate a different one + simulate: function( type, elem, event ) { + var e = jQuery.extend( + new jQuery.Event(), + event, + { + type: type, + isSimulated: true + + // Previously, `originalEvent: {}` was set here, so stopPropagation call + // would not be triggered on donor event, since in our own + // jQuery.event.stopPropagation function we had a check for existence of + // originalEvent.stopPropagation method, so, consequently it would be a noop. + // + // But now, this "simulate" function is used only for events + // for which stopPropagation() is noop, so there is no need for that anymore. + // + // For the compat branch though, guard for "click" and "submit" + // events is still used, but was moved to jQuery.event.stopPropagation function + // because `originalEvent` should point to the original event for the constancy + // with other events and for more focused logic + } + ); + + jQuery.event.trigger( e, null, elem ); + + if ( e.isDefaultPrevented() ) { + event.preventDefault(); + } + } + +} ); + +jQuery.fn.extend( { + + trigger: function( type, data ) { + return this.each( function() { + jQuery.event.trigger( type, data, this ); + } ); + }, + triggerHandler: function( type, data ) { + var elem = this[ 0 ]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + } +} ); + + +jQuery.each( ( "blur focus focusin focusout load resize scroll unload click dblclick " + + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + + "change select submit keydown keypress keyup error contextmenu" ).split( " " ), + function( i, name ) { + + // Handle event binding + jQuery.fn[ name ] = function( data, fn ) { + return arguments.length > 0 ? + this.on( name, null, data, fn ) : + this.trigger( name ); + }; +} ); + +jQuery.fn.extend( { + hover: function( fnOver, fnOut ) { + return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); + } +} ); + + + + +support.focusin = "onfocusin" in window; + + +// Support: Firefox +// Firefox doesn't have focus(in | out) events +// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 +// +// Support: Chrome, Safari +// focus(in | out) events fire after focus & blur events, +// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order +// Related ticket - https://code.google.com/p/chromium/issues/detail?id=449857 +if ( !support.focusin ) { + jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler on the document while someone wants focusin/focusout + var handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + var doc = this.ownerDocument || this, + attaches = dataPriv.access( doc, fix ); + + if ( !attaches ) { + doc.addEventListener( orig, handler, true ); + } + dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); + }, + teardown: function() { + var doc = this.ownerDocument || this, + attaches = dataPriv.access( doc, fix ) - 1; + + if ( !attaches ) { + doc.removeEventListener( orig, handler, true ); + dataPriv.remove( doc, fix ); + + } else { + dataPriv.access( doc, fix, attaches ); + } + } + }; + } ); +} +var location = window.location; + +var nonce = jQuery.now(); + +var rquery = ( /\?/ ); + + + +// Support: Android 2.3 +// Workaround failure to string-cast null input +jQuery.parseJSON = function( data ) { + return JSON.parse( data + "" ); +}; + + +// Cross-browser xml parsing +jQuery.parseXML = function( data ) { + var xml; + if ( !data || typeof data !== "string" ) { + return null; + } + + // Support: IE9 + try { + xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); + } catch ( e ) { + xml = undefined; + } + + if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; +}; + + +var + rhash = /#.*$/, + rts = /([?&])_=[^&]*/, + rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, + + // #7653, #8125, #8152: local protocol detection + rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, + rnoContent = /^(?:GET|HEAD)$/, + rprotocol = /^\/\//, + + /* Prefilters + * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) + * 2) These are called: + * - BEFORE asking for a transport + * - AFTER param serialization (s.data is a string if s.processData is true) + * 3) key is the dataType + * 4) the catchall symbol "*" can be used + * 5) execution will start with transport dataType and THEN continue down to "*" if needed + */ + prefilters = {}, + + /* Transports bindings + * 1) key is the dataType + * 2) the catchall symbol "*" can be used + * 3) selection will start with transport dataType and THEN go to "*" if needed + */ + transports = {}, + + // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression + allTypes = "*/".concat( "*" ), + + // Anchor tag for parsing the document origin + originAnchor = document.createElement( "a" ); + originAnchor.href = location.href; + +// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport +function addToPrefiltersOrTransports( structure ) { + + // dataTypeExpression is optional and defaults to "*" + return function( dataTypeExpression, func ) { + + if ( typeof dataTypeExpression !== "string" ) { + func = dataTypeExpression; + dataTypeExpression = "*"; + } + + var dataType, + i = 0, + dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || []; + + if ( jQuery.isFunction( func ) ) { + + // For each dataType in the dataTypeExpression + while ( ( dataType = dataTypes[ i++ ] ) ) { + + // Prepend if requested + if ( dataType[ 0 ] === "+" ) { + dataType = dataType.slice( 1 ) || "*"; + ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); + + // Otherwise append + } else { + ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); + } + } + } + }; +} + +// Base inspection function for prefilters and transports +function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { + + var inspected = {}, + seekingTransport = ( structure === transports ); + + function inspect( dataType ) { + var selected; + inspected[ dataType ] = true; + jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { + var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); + if ( typeof dataTypeOrTransport === "string" && + !seekingTransport && !inspected[ dataTypeOrTransport ] ) { + + options.dataTypes.unshift( dataTypeOrTransport ); + inspect( dataTypeOrTransport ); + return false; + } else if ( seekingTransport ) { + return !( selected = dataTypeOrTransport ); + } + } ); + return selected; + } + + return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); +} + +// A special extend for ajax options +// that takes "flat" options (not to be deep extended) +// Fixes #9887 +function ajaxExtend( target, src ) { + var key, deep, + flatOptions = jQuery.ajaxSettings.flatOptions || {}; + + for ( key in src ) { + if ( src[ key ] !== undefined ) { + ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; + } + } + if ( deep ) { + jQuery.extend( true, target, deep ); + } + + return target; +} + +/* Handles responses to an ajax request: + * - finds the right dataType (mediates between content-type and expected dataType) + * - returns the corresponding response + */ +function ajaxHandleResponses( s, jqXHR, responses ) { + + var ct, type, finalDataType, firstDataType, + contents = s.contents, + dataTypes = s.dataTypes; + + // Remove auto dataType and get content-type in the process + while ( dataTypes[ 0 ] === "*" ) { + dataTypes.shift(); + if ( ct === undefined ) { + ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); + } + } + + // Check if we're dealing with a known content-type + if ( ct ) { + for ( type in contents ) { + if ( contents[ type ] && contents[ type ].test( ct ) ) { + dataTypes.unshift( type ); + break; + } + } + } + + // Check to see if we have a response for the expected dataType + if ( dataTypes[ 0 ] in responses ) { + finalDataType = dataTypes[ 0 ]; + } else { + + // Try convertible dataTypes + for ( type in responses ) { + if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { + finalDataType = type; + break; + } + if ( !firstDataType ) { + firstDataType = type; + } + } + + // Or just use first one + finalDataType = finalDataType || firstDataType; + } + + // If we found a dataType + // We add the dataType to the list if needed + // and return the corresponding response + if ( finalDataType ) { + if ( finalDataType !== dataTypes[ 0 ] ) { + dataTypes.unshift( finalDataType ); + } + return responses[ finalDataType ]; + } +} + +/* Chain conversions given the request and the original response + * Also sets the responseXXX fields on the jqXHR instance + */ +function ajaxConvert( s, response, jqXHR, isSuccess ) { + var conv2, current, conv, tmp, prev, + converters = {}, + + // Work with a copy of dataTypes in case we need to modify it for conversion + dataTypes = s.dataTypes.slice(); + + // Create converters map with lowercased keys + if ( dataTypes[ 1 ] ) { + for ( conv in s.converters ) { + converters[ conv.toLowerCase() ] = s.converters[ conv ]; + } + } + + current = dataTypes.shift(); + + // Convert to each sequential dataType + while ( current ) { + + if ( s.responseFields[ current ] ) { + jqXHR[ s.responseFields[ current ] ] = response; + } + + // Apply the dataFilter if provided + if ( !prev && isSuccess && s.dataFilter ) { + response = s.dataFilter( response, s.dataType ); + } + + prev = current; + current = dataTypes.shift(); + + if ( current ) { + + // There's only work to do if current dataType is non-auto + if ( current === "*" ) { + + current = prev; + + // Convert response if prev dataType is non-auto and differs from current + } else if ( prev !== "*" && prev !== current ) { + + // Seek a direct converter + conv = converters[ prev + " " + current ] || converters[ "* " + current ]; + + // If none found, seek a pair + if ( !conv ) { + for ( conv2 in converters ) { + + // If conv2 outputs current + tmp = conv2.split( " " ); + if ( tmp[ 1 ] === current ) { + + // If prev can be converted to accepted input + conv = converters[ prev + " " + tmp[ 0 ] ] || + converters[ "* " + tmp[ 0 ] ]; + if ( conv ) { + + // Condense equivalence converters + if ( conv === true ) { + conv = converters[ conv2 ]; + + // Otherwise, insert the intermediate dataType + } else if ( converters[ conv2 ] !== true ) { + current = tmp[ 0 ]; + dataTypes.unshift( tmp[ 1 ] ); + } + break; + } + } + } + } + + // Apply converter (if not an equivalence) + if ( conv !== true ) { + + // Unless errors are allowed to bubble, catch and return them + if ( conv && s.throws ) { + response = conv( response ); + } else { + try { + response = conv( response ); + } catch ( e ) { + return { + state: "parsererror", + error: conv ? e : "No conversion from " + prev + " to " + current + }; + } + } + } + } + } + } + + return { state: "success", data: response }; +} + +jQuery.extend( { + + // Counter for holding the number of active queries + active: 0, + + // Last-Modified header cache for next request + lastModified: {}, + etag: {}, + + ajaxSettings: { + url: location.href, + type: "GET", + isLocal: rlocalProtocol.test( location.protocol ), + global: true, + processData: true, + async: true, + contentType: "application/x-www-form-urlencoded; charset=UTF-8", + /* + timeout: 0, + data: null, + dataType: null, + username: null, + password: null, + cache: null, + throws: false, + traditional: false, + headers: {}, + */ + + accepts: { + "*": allTypes, + text: "text/plain", + html: "text/html", + xml: "application/xml, text/xml", + json: "application/json, text/javascript" + }, + + contents: { + xml: /\bxml\b/, + html: /\bhtml/, + json: /\bjson\b/ + }, + + responseFields: { + xml: "responseXML", + text: "responseText", + json: "responseJSON" + }, + + // Data converters + // Keys separate source (or catchall "*") and destination types with a single space + converters: { + + // Convert anything to text + "* text": String, + + // Text to html (true = no transformation) + "text html": true, + + // Evaluate text as a json expression + "text json": jQuery.parseJSON, + + // Parse text as xml + "text xml": jQuery.parseXML + }, + + // For options that shouldn't be deep extended: + // you can add your own custom options here if + // and when you create one that shouldn't be + // deep extended (see ajaxExtend) + flatOptions: { + url: true, + context: true + } + }, + + // Creates a full fledged settings object into target + // with both ajaxSettings and settings fields. + // If target is omitted, writes into ajaxSettings. + ajaxSetup: function( target, settings ) { + return settings ? + + // Building a settings object + ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : + + // Extending ajaxSettings + ajaxExtend( jQuery.ajaxSettings, target ); + }, + + ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), + ajaxTransport: addToPrefiltersOrTransports( transports ), + + // Main method + ajax: function( url, options ) { + + // If url is an object, simulate pre-1.5 signature + if ( typeof url === "object" ) { + options = url; + url = undefined; + } + + // Force options to be an object + options = options || {}; + + var transport, + + // URL without anti-cache param + cacheURL, + + // Response headers + responseHeadersString, + responseHeaders, + + // timeout handle + timeoutTimer, + + // Url cleanup var + urlAnchor, + + // To know if global events are to be dispatched + fireGlobals, + + // Loop variable + i, + + // Create the final options object + s = jQuery.ajaxSetup( {}, options ), + + // Callbacks context + callbackContext = s.context || s, + + // Context for global events is callbackContext if it is a DOM node or jQuery collection + globalEventContext = s.context && + ( callbackContext.nodeType || callbackContext.jquery ) ? + jQuery( callbackContext ) : + jQuery.event, + + // Deferreds + deferred = jQuery.Deferred(), + completeDeferred = jQuery.Callbacks( "once memory" ), + + // Status-dependent callbacks + statusCode = s.statusCode || {}, + + // Headers (they are sent all at once) + requestHeaders = {}, + requestHeadersNames = {}, + + // The jqXHR state + state = 0, + + // Default abort message + strAbort = "canceled", + + // Fake xhr + jqXHR = { + readyState: 0, + + // Builds headers hashtable if needed + getResponseHeader: function( key ) { + var match; + if ( state === 2 ) { + if ( !responseHeaders ) { + responseHeaders = {}; + while ( ( match = rheaders.exec( responseHeadersString ) ) ) { + responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ]; + } + } + match = responseHeaders[ key.toLowerCase() ]; + } + return match == null ? null : match; + }, + + // Raw string + getAllResponseHeaders: function() { + return state === 2 ? responseHeadersString : null; + }, + + // Caches the header + setRequestHeader: function( name, value ) { + var lname = name.toLowerCase(); + if ( !state ) { + name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; + requestHeaders[ name ] = value; + } + return this; + }, + + // Overrides response content-type header + overrideMimeType: function( type ) { + if ( !state ) { + s.mimeType = type; + } + return this; + }, + + // Status-dependent callbacks + statusCode: function( map ) { + var code; + if ( map ) { + if ( state < 2 ) { + for ( code in map ) { + + // Lazy-add the new callback in a way that preserves old ones + statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; + } + } else { + + // Execute the appropriate callbacks + jqXHR.always( map[ jqXHR.status ] ); + } + } + return this; + }, + + // Cancel the request + abort: function( statusText ) { + var finalText = statusText || strAbort; + if ( transport ) { + transport.abort( finalText ); + } + done( 0, finalText ); + return this; + } + }; + + // Attach deferreds + deferred.promise( jqXHR ).complete = completeDeferred.add; + jqXHR.success = jqXHR.done; + jqXHR.error = jqXHR.fail; + + // Remove hash character (#7531: and string promotion) + // Add protocol if not provided (prefilters might expect it) + // Handle falsy url in the settings object (#10093: consistency with old signature) + // We also use the url parameter if available + s.url = ( ( url || s.url || location.href ) + "" ).replace( rhash, "" ) + .replace( rprotocol, location.protocol + "//" ); + + // Alias method option to type as per ticket #12004 + s.type = options.method || options.type || s.method || s.type; + + // Extract dataTypes list + s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ]; + + // A cross-domain request is in order when the origin doesn't match the current origin. + if ( s.crossDomain == null ) { + urlAnchor = document.createElement( "a" ); + + // Support: IE8-11+ + // IE throws exception if url is malformed, e.g. http://example.com:80x/ + try { + urlAnchor.href = s.url; + + // Support: IE8-11+ + // Anchor's host property isn't correctly set when s.url is relative + urlAnchor.href = urlAnchor.href; + s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== + urlAnchor.protocol + "//" + urlAnchor.host; + } catch ( e ) { + + // If there is an error parsing the URL, assume it is crossDomain, + // it can be rejected by the transport if it is invalid + s.crossDomain = true; + } + } + + // Convert data if not already a string + if ( s.data && s.processData && typeof s.data !== "string" ) { + s.data = jQuery.param( s.data, s.traditional ); + } + + // Apply prefilters + inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); + + // If request was aborted inside a prefilter, stop there + if ( state === 2 ) { + return jqXHR; + } + + // We can fire global events as of now if asked to + // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) + fireGlobals = jQuery.event && s.global; + + // Watch for a new set of requests + if ( fireGlobals && jQuery.active++ === 0 ) { + jQuery.event.trigger( "ajaxStart" ); + } + + // Uppercase the type + s.type = s.type.toUpperCase(); + + // Determine if request has content + s.hasContent = !rnoContent.test( s.type ); + + // Save the URL in case we're toying with the If-Modified-Since + // and/or If-None-Match header later on + cacheURL = s.url; + + // More options handling for requests with no content + if ( !s.hasContent ) { + + // If data is available, append data to url + if ( s.data ) { + cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); + + // #9682: remove data so that it's not used in an eventual retry + delete s.data; + } + + // Add anti-cache in url if needed + if ( s.cache === false ) { + s.url = rts.test( cacheURL ) ? + + // If there is already a '_' parameter, set its value + cacheURL.replace( rts, "$1_=" + nonce++ ) : + + // Otherwise add one to the end + cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++; + } + } + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + if ( jQuery.lastModified[ cacheURL ] ) { + jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); + } + if ( jQuery.etag[ cacheURL ] ) { + jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); + } + } + + // Set the correct header, if data is being sent + if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { + jqXHR.setRequestHeader( "Content-Type", s.contentType ); + } + + // Set the Accepts header for the server, depending on the dataType + jqXHR.setRequestHeader( + "Accept", + s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? + s.accepts[ s.dataTypes[ 0 ] ] + + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : + s.accepts[ "*" ] + ); + + // Check for headers option + for ( i in s.headers ) { + jqXHR.setRequestHeader( i, s.headers[ i ] ); + } + + // Allow custom headers/mimetypes and early abort + if ( s.beforeSend && + ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { + + // Abort if not done already and return + return jqXHR.abort(); + } + + // Aborting is no longer a cancellation + strAbort = "abort"; + + // Install callbacks on deferreds + for ( i in { success: 1, error: 1, complete: 1 } ) { + jqXHR[ i ]( s[ i ] ); + } + + // Get transport + transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); + + // If no transport, we auto-abort + if ( !transport ) { + done( -1, "No Transport" ); + } else { + jqXHR.readyState = 1; + + // Send global event + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); + } + + // If request was aborted inside ajaxSend, stop there + if ( state === 2 ) { + return jqXHR; + } + + // Timeout + if ( s.async && s.timeout > 0 ) { + timeoutTimer = window.setTimeout( function() { + jqXHR.abort( "timeout" ); + }, s.timeout ); + } + + try { + state = 1; + transport.send( requestHeaders, done ); + } catch ( e ) { + + // Propagate exception as error if not done + if ( state < 2 ) { + done( -1, e ); + + // Simply rethrow otherwise + } else { + throw e; + } + } + } + + // Callback for when everything is done + function done( status, nativeStatusText, responses, headers ) { + var isSuccess, success, error, response, modified, + statusText = nativeStatusText; + + // Called once + if ( state === 2 ) { + return; + } + + // State is "done" now + state = 2; + + // Clear timeout if it exists + if ( timeoutTimer ) { + window.clearTimeout( timeoutTimer ); + } + + // Dereference transport for early garbage collection + // (no matter how long the jqXHR object will be used) + transport = undefined; + + // Cache response headers + responseHeadersString = headers || ""; + + // Set readyState + jqXHR.readyState = status > 0 ? 4 : 0; + + // Determine if successful + isSuccess = status >= 200 && status < 300 || status === 304; + + // Get response data + if ( responses ) { + response = ajaxHandleResponses( s, jqXHR, responses ); + } + + // Convert no matter what (that way responseXXX fields are always set) + response = ajaxConvert( s, response, jqXHR, isSuccess ); + + // If successful, handle type chaining + if ( isSuccess ) { + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + modified = jqXHR.getResponseHeader( "Last-Modified" ); + if ( modified ) { + jQuery.lastModified[ cacheURL ] = modified; + } + modified = jqXHR.getResponseHeader( "etag" ); + if ( modified ) { + jQuery.etag[ cacheURL ] = modified; + } + } + + // if no content + if ( status === 204 || s.type === "HEAD" ) { + statusText = "nocontent"; + + // if not modified + } else if ( status === 304 ) { + statusText = "notmodified"; + + // If we have data, let's convert it + } else { + statusText = response.state; + success = response.data; + error = response.error; + isSuccess = !error; + } + } else { + + // Extract error from statusText and normalize for non-aborts + error = statusText; + if ( status || !statusText ) { + statusText = "error"; + if ( status < 0 ) { + status = 0; + } + } + } + + // Set data for the fake xhr object + jqXHR.status = status; + jqXHR.statusText = ( nativeStatusText || statusText ) + ""; + + // Success/Error + if ( isSuccess ) { + deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); + } else { + deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); + } + + // Status-dependent callbacks + jqXHR.statusCode( statusCode ); + statusCode = undefined; + + if ( fireGlobals ) { + globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", + [ jqXHR, s, isSuccess ? success : error ] ); + } + + // Complete + completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); + + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); + + // Handle the global AJAX counter + if ( !( --jQuery.active ) ) { + jQuery.event.trigger( "ajaxStop" ); + } + } + } + + return jqXHR; + }, + + getJSON: function( url, data, callback ) { + return jQuery.get( url, data, callback, "json" ); + }, + + getScript: function( url, callback ) { + return jQuery.get( url, undefined, callback, "script" ); + } +} ); + +jQuery.each( [ "get", "post" ], function( i, method ) { + jQuery[ method ] = function( url, data, callback, type ) { + + // Shift arguments if data argument was omitted + if ( jQuery.isFunction( data ) ) { + type = type || callback; + callback = data; + data = undefined; + } + + // The url can be an options object (which then must have .url) + return jQuery.ajax( jQuery.extend( { + url: url, + type: method, + dataType: type, + data: data, + success: callback + }, jQuery.isPlainObject( url ) && url ) ); + }; +} ); + + +jQuery._evalUrl = function( url ) { + return jQuery.ajax( { + url: url, + + // Make this explicit, since user can override this through ajaxSetup (#11264) + type: "GET", + dataType: "script", + async: false, + global: false, + "throws": true + } ); +}; + + +jQuery.fn.extend( { + wrapAll: function( html ) { + var wrap; + + if ( jQuery.isFunction( html ) ) { + return this.each( function( i ) { + jQuery( this ).wrapAll( html.call( this, i ) ); + } ); + } + + if ( this[ 0 ] ) { + + // The elements to wrap the target around + wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); + + if ( this[ 0 ].parentNode ) { + wrap.insertBefore( this[ 0 ] ); + } + + wrap.map( function() { + var elem = this; + + while ( elem.firstElementChild ) { + elem = elem.firstElementChild; + } + + return elem; + } ).append( this ); + } + + return this; + }, + + wrapInner: function( html ) { + if ( jQuery.isFunction( html ) ) { + return this.each( function( i ) { + jQuery( this ).wrapInner( html.call( this, i ) ); + } ); + } + + return this.each( function() { + var self = jQuery( this ), + contents = self.contents(); + + if ( contents.length ) { + contents.wrapAll( html ); + + } else { + self.append( html ); + } + } ); + }, + + wrap: function( html ) { + var isFunction = jQuery.isFunction( html ); + + return this.each( function( i ) { + jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html ); + } ); + }, + + unwrap: function() { + return this.parent().each( function() { + if ( !jQuery.nodeName( this, "body" ) ) { + jQuery( this ).replaceWith( this.childNodes ); + } + } ).end(); + } +} ); + + +jQuery.expr.filters.hidden = function( elem ) { + return !jQuery.expr.filters.visible( elem ); +}; +jQuery.expr.filters.visible = function( elem ) { + + // Support: Opera <= 12.12 + // Opera reports offsetWidths and offsetHeights less than zero on some elements + // Use OR instead of AND as the element is not visible if either is true + // See tickets #10406 and #13132 + return elem.offsetWidth > 0 || elem.offsetHeight > 0 || elem.getClientRects().length > 0; +}; + + + + +var r20 = /%20/g, + rbracket = /\[\]$/, + rCRLF = /\r?\n/g, + rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, + rsubmittable = /^(?:input|select|textarea|keygen)/i; + +function buildParams( prefix, obj, traditional, add ) { + var name; + + if ( jQuery.isArray( obj ) ) { + + // Serialize array item. + jQuery.each( obj, function( i, v ) { + if ( traditional || rbracket.test( prefix ) ) { + + // Treat each array item as a scalar. + add( prefix, v ); + + } else { + + // Item is non-scalar (array or object), encode its numeric index. + buildParams( + prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", + v, + traditional, + add + ); + } + } ); + + } else if ( !traditional && jQuery.type( obj ) === "object" ) { + + // Serialize object item. + for ( name in obj ) { + buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); + } + + } else { + + // Serialize scalar item. + add( prefix, obj ); + } +} + +// Serialize an array of form elements or a set of +// key/values into a query string +jQuery.param = function( a, traditional ) { + var prefix, + s = [], + add = function( key, value ) { + + // If value is a function, invoke it and return its value + value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); + s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); + }; + + // Set traditional to true for jQuery <= 1.3.2 behavior. + if ( traditional === undefined ) { + traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; + } + + // If an array was passed in, assume that it is an array of form elements. + if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { + + // Serialize the form elements + jQuery.each( a, function() { + add( this.name, this.value ); + } ); + + } else { + + // If traditional, encode the "old" way (the way 1.3.2 or older + // did it), otherwise encode params recursively. + for ( prefix in a ) { + buildParams( prefix, a[ prefix ], traditional, add ); + } + } + + // Return the resulting serialization + return s.join( "&" ).replace( r20, "+" ); +}; + +jQuery.fn.extend( { + serialize: function() { + return jQuery.param( this.serializeArray() ); + }, + serializeArray: function() { + return this.map( function() { + + // Can add propHook for "elements" to filter or add form elements + var elements = jQuery.prop( this, "elements" ); + return elements ? jQuery.makeArray( elements ) : this; + } ) + .filter( function() { + var type = this.type; + + // Use .is( ":disabled" ) so that fieldset[disabled] works + return this.name && !jQuery( this ).is( ":disabled" ) && + rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && + ( this.checked || !rcheckableType.test( type ) ); + } ) + .map( function( i, elem ) { + var val = jQuery( this ).val(); + + return val == null ? + null : + jQuery.isArray( val ) ? + jQuery.map( val, function( val ) { + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ) : + { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ).get(); + } +} ); + + +jQuery.ajaxSettings.xhr = function() { + try { + return new window.XMLHttpRequest(); + } catch ( e ) {} +}; + +var xhrSuccessStatus = { + + // File protocol always yields status code 0, assume 200 + 0: 200, + + // Support: IE9 + // #1450: sometimes IE returns 1223 when it should be 204 + 1223: 204 + }, + xhrSupported = jQuery.ajaxSettings.xhr(); + +support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); +support.ajax = xhrSupported = !!xhrSupported; + +jQuery.ajaxTransport( function( options ) { + var callback, errorCallback; + + // Cross domain only allowed if supported through XMLHttpRequest + if ( support.cors || xhrSupported && !options.crossDomain ) { + return { + send: function( headers, complete ) { + var i, + xhr = options.xhr(); + + xhr.open( + options.type, + options.url, + options.async, + options.username, + options.password + ); + + // Apply custom fields if provided + if ( options.xhrFields ) { + for ( i in options.xhrFields ) { + xhr[ i ] = options.xhrFields[ i ]; + } + } + + // Override mime type if needed + if ( options.mimeType && xhr.overrideMimeType ) { + xhr.overrideMimeType( options.mimeType ); + } + + // X-Requested-With header + // For cross-domain requests, seeing as conditions for a preflight are + // akin to a jigsaw puzzle, we simply never set it to be sure. + // (it can always be set on a per-request basis or even using ajaxSetup) + // For same-domain requests, won't change header if already provided. + if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { + headers[ "X-Requested-With" ] = "XMLHttpRequest"; + } + + // Set headers + for ( i in headers ) { + xhr.setRequestHeader( i, headers[ i ] ); + } + + // Callback + callback = function( type ) { + return function() { + if ( callback ) { + callback = errorCallback = xhr.onload = + xhr.onerror = xhr.onabort = xhr.onreadystatechange = null; + + if ( type === "abort" ) { + xhr.abort(); + } else if ( type === "error" ) { + + // Support: IE9 + // On a manual native abort, IE9 throws + // errors on any property access that is not readyState + if ( typeof xhr.status !== "number" ) { + complete( 0, "error" ); + } else { + complete( + + // File: protocol always yields status 0; see #8605, #14207 + xhr.status, + xhr.statusText + ); + } + } else { + complete( + xhrSuccessStatus[ xhr.status ] || xhr.status, + xhr.statusText, + + // Support: IE9 only + // IE9 has no XHR2 but throws on binary (trac-11426) + // For XHR2 non-text, let the caller handle it (gh-2498) + ( xhr.responseType || "text" ) !== "text" || + typeof xhr.responseText !== "string" ? + { binary: xhr.response } : + { text: xhr.responseText }, + xhr.getAllResponseHeaders() + ); + } + } + }; + }; + + // Listen to events + xhr.onload = callback(); + errorCallback = xhr.onerror = callback( "error" ); + + // Support: IE9 + // Use onreadystatechange to replace onabort + // to handle uncaught aborts + if ( xhr.onabort !== undefined ) { + xhr.onabort = errorCallback; + } else { + xhr.onreadystatechange = function() { + + // Check readyState before timeout as it changes + if ( xhr.readyState === 4 ) { + + // Allow onerror to be called first, + // but that will not handle a native abort + // Also, save errorCallback to a variable + // as xhr.onerror cannot be accessed + window.setTimeout( function() { + if ( callback ) { + errorCallback(); + } + } ); + } + }; + } + + // Create the abort callback + callback = callback( "abort" ); + + try { + + // Do send the request (this may raise an exception) + xhr.send( options.hasContent && options.data || null ); + } catch ( e ) { + + // #14683: Only rethrow if this hasn't been notified as an error yet + if ( callback ) { + throw e; + } + } + }, + + abort: function() { + if ( callback ) { + callback(); + } + } + }; + } +} ); + + + + +// Install script dataType +jQuery.ajaxSetup( { + accepts: { + script: "text/javascript, application/javascript, " + + "application/ecmascript, application/x-ecmascript" + }, + contents: { + script: /\b(?:java|ecma)script\b/ + }, + converters: { + "text script": function( text ) { + jQuery.globalEval( text ); + return text; + } + } +} ); + +// Handle cache's special case and crossDomain +jQuery.ajaxPrefilter( "script", function( s ) { + if ( s.cache === undefined ) { + s.cache = false; + } + if ( s.crossDomain ) { + s.type = "GET"; + } +} ); + +// Bind script tag hack transport +jQuery.ajaxTransport( "script", function( s ) { + + // This transport only deals with cross domain requests + if ( s.crossDomain ) { + var script, callback; + return { + send: function( _, complete ) { + script = jQuery( "<script>" ).prop( { + charset: s.scriptCharset, + src: s.url + } ).on( + "load error", + callback = function( evt ) { + script.remove(); + callback = null; + if ( evt ) { + complete( evt.type === "error" ? 404 : 200, evt.type ); + } + } + ); + + // Use native DOM manipulation to avoid our domManip AJAX trickery + document.head.appendChild( script[ 0 ] ); + }, + abort: function() { + if ( callback ) { + callback(); + } + } + }; + } +} ); + + + + +var oldCallbacks = [], + rjsonp = /(=)\?(?=&|$)|\?\?/; + +// Default jsonp settings +jQuery.ajaxSetup( { + jsonp: "callback", + jsonpCallback: function() { + var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); + this[ callback ] = true; + return callback; + } +} ); + +// Detect, normalize options and install callbacks for jsonp requests +jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { + + var callbackName, overwritten, responseContainer, + jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? + "url" : + typeof s.data === "string" && + ( s.contentType || "" ) + .indexOf( "application/x-www-form-urlencoded" ) === 0 && + rjsonp.test( s.data ) && "data" + ); + + // Handle iff the expected data type is "jsonp" or we have a parameter to set + if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { + + // Get callback name, remembering preexisting value associated with it + callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? + s.jsonpCallback() : + s.jsonpCallback; + + // Insert callback into url or form data + if ( jsonProp ) { + s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); + } else if ( s.jsonp !== false ) { + s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; + } + + // Use data converter to retrieve json after script execution + s.converters[ "script json" ] = function() { + if ( !responseContainer ) { + jQuery.error( callbackName + " was not called" ); + } + return responseContainer[ 0 ]; + }; + + // Force json dataType + s.dataTypes[ 0 ] = "json"; + + // Install callback + overwritten = window[ callbackName ]; + window[ callbackName ] = function() { + responseContainer = arguments; + }; + + // Clean-up function (fires after converters) + jqXHR.always( function() { + + // If previous value didn't exist - remove it + if ( overwritten === undefined ) { + jQuery( window ).removeProp( callbackName ); + + // Otherwise restore preexisting value + } else { + window[ callbackName ] = overwritten; + } + + // Save back as free + if ( s[ callbackName ] ) { + + // Make sure that re-using the options doesn't screw things around + s.jsonpCallback = originalSettings.jsonpCallback; + + // Save the callback name for future use + oldCallbacks.push( callbackName ); + } + + // Call if it was a function and we have a response + if ( responseContainer && jQuery.isFunction( overwritten ) ) { + overwritten( responseContainer[ 0 ] ); + } + + responseContainer = overwritten = undefined; + } ); + + // Delegate to script + return "script"; + } +} ); + + + + +// Support: Safari 8+ +// In Safari 8 documents created via document.implementation.createHTMLDocument +// collapse sibling forms: the second one becomes a child of the first one. +// Because of that, this security measure has to be disabled in Safari 8. +// https://bugs.webkit.org/show_bug.cgi?id=137337 +support.createHTMLDocument = ( function() { + var body = document.implementation.createHTMLDocument( "" ).body; + body.innerHTML = "<form></form><form></form>"; + return body.childNodes.length === 2; +} )(); + + +// Argument "data" should be string of html +// context (optional): If specified, the fragment will be created in this context, +// defaults to document +// keepScripts (optional): If true, will include scripts passed in the html string +jQuery.parseHTML = function( data, context, keepScripts ) { + if ( !data || typeof data !== "string" ) { + return null; + } + if ( typeof context === "boolean" ) { + keepScripts = context; + context = false; + } + + // Stop scripts or inline event handlers from being executed immediately + // by using document.implementation + context = context || ( support.createHTMLDocument ? + document.implementation.createHTMLDocument( "" ) : + document ); + + var parsed = rsingleTag.exec( data ), + scripts = !keepScripts && []; + + // Single tag + if ( parsed ) { + return [ context.createElement( parsed[ 1 ] ) ]; + } + + parsed = buildFragment( [ data ], context, scripts ); + + if ( scripts && scripts.length ) { + jQuery( scripts ).remove(); + } + + return jQuery.merge( [], parsed.childNodes ); +}; + + +// Keep a copy of the old load method +var _load = jQuery.fn.load; + +/** + * Load a url into a page + */ +jQuery.fn.load = function( url, params, callback ) { + if ( typeof url !== "string" && _load ) { + return _load.apply( this, arguments ); + } + + var selector, type, response, + self = this, + off = url.indexOf( " " ); + + if ( off > -1 ) { + selector = jQuery.trim( url.slice( off ) ); + url = url.slice( 0, off ); + } + + // If it's a function + if ( jQuery.isFunction( params ) ) { + + // We assume that it's the callback + callback = params; + params = undefined; + + // Otherwise, build a param string + } else if ( params && typeof params === "object" ) { + type = "POST"; + } + + // If we have elements to modify, make the request + if ( self.length > 0 ) { + jQuery.ajax( { + url: url, + + // If "type" variable is undefined, then "GET" method will be used. + // Make value of this field explicit since + // user can override it through ajaxSetup method + type: type || "GET", + dataType: "html", + data: params + } ).done( function( responseText ) { + + // Save response for use in complete callback + response = arguments; + + self.html( selector ? + + // If a selector was specified, locate the right elements in a dummy div + // Exclude scripts to avoid IE 'Permission Denied' errors + jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) : + + // Otherwise use the full result + responseText ); + + // If the request succeeds, this function gets "data", "status", "jqXHR" + // but they are ignored because response was set above. + // If it fails, this function gets "jqXHR", "status", "error" + } ).always( callback && function( jqXHR, status ) { + self.each( function() { + callback.apply( self, response || [ jqXHR.responseText, status, jqXHR ] ); + } ); + } ); + } + + return this; +}; + + + + +// Attach a bunch of functions for handling common AJAX events +jQuery.each( [ + "ajaxStart", + "ajaxStop", + "ajaxComplete", + "ajaxError", + "ajaxSuccess", + "ajaxSend" +], function( i, type ) { + jQuery.fn[ type ] = function( fn ) { + return this.on( type, fn ); + }; +} ); + + + + +jQuery.expr.filters.animated = function( elem ) { + return jQuery.grep( jQuery.timers, function( fn ) { + return elem === fn.elem; + } ).length; +}; + + + + +/** + * Gets a window from an element + */ +function getWindow( elem ) { + return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView; +} + +jQuery.offset = { + setOffset: function( elem, options, i ) { + var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, + position = jQuery.css( elem, "position" ), + curElem = jQuery( elem ), + props = {}; + + // Set position first, in-case top/left are set even on static elem + if ( position === "static" ) { + elem.style.position = "relative"; + } + + curOffset = curElem.offset(); + curCSSTop = jQuery.css( elem, "top" ); + curCSSLeft = jQuery.css( elem, "left" ); + calculatePosition = ( position === "absolute" || position === "fixed" ) && + ( curCSSTop + curCSSLeft ).indexOf( "auto" ) > -1; + + // Need to be able to calculate position if either + // top or left is auto and position is either absolute or fixed + if ( calculatePosition ) { + curPosition = curElem.position(); + curTop = curPosition.top; + curLeft = curPosition.left; + + } else { + curTop = parseFloat( curCSSTop ) || 0; + curLeft = parseFloat( curCSSLeft ) || 0; + } + + if ( jQuery.isFunction( options ) ) { + + // Use jQuery.extend here to allow modification of coordinates argument (gh-1848) + options = options.call( elem, i, jQuery.extend( {}, curOffset ) ); + } + + if ( options.top != null ) { + props.top = ( options.top - curOffset.top ) + curTop; + } + if ( options.left != null ) { + props.left = ( options.left - curOffset.left ) + curLeft; + } + + if ( "using" in options ) { + options.using.call( elem, props ); + + } else { + curElem.css( props ); + } + } +}; + +jQuery.fn.extend( { + offset: function( options ) { + if ( arguments.length ) { + return options === undefined ? + this : + this.each( function( i ) { + jQuery.offset.setOffset( this, options, i ); + } ); + } + + var docElem, win, + elem = this[ 0 ], + box = { top: 0, left: 0 }, + doc = elem && elem.ownerDocument; + + if ( !doc ) { + return; + } + + docElem = doc.documentElement; + + // Make sure it's not a disconnected DOM node + if ( !jQuery.contains( docElem, elem ) ) { + return box; + } + + box = elem.getBoundingClientRect(); + win = getWindow( doc ); + return { + top: box.top + win.pageYOffset - docElem.clientTop, + left: box.left + win.pageXOffset - docElem.clientLeft + }; + }, + + position: function() { + if ( !this[ 0 ] ) { + return; + } + + var offsetParent, offset, + elem = this[ 0 ], + parentOffset = { top: 0, left: 0 }; + + // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, + // because it is its only offset parent + if ( jQuery.css( elem, "position" ) === "fixed" ) { + + // Assume getBoundingClientRect is there when computed position is fixed + offset = elem.getBoundingClientRect(); + + } else { + + // Get *real* offsetParent + offsetParent = this.offsetParent(); + + // Get correct offsets + offset = this.offset(); + if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { + parentOffset = offsetParent.offset(); + } + + // Add offsetParent borders + // Subtract offsetParent scroll positions + parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ) - + offsetParent.scrollTop(); + parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ) - + offsetParent.scrollLeft(); + } + + // Subtract parent offsets and element margins + return { + top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), + left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true ) + }; + }, + + // This method will return documentElement in the following cases: + // 1) For the element inside the iframe without offsetParent, this method will return + // documentElement of the parent window + // 2) For the hidden or detached element + // 3) For body or html element, i.e. in case of the html node - it will return itself + // + // but those exceptions were never presented as a real life use-cases + // and might be considered as more preferable results. + // + // This logic, however, is not guaranteed and can change at any point in the future + offsetParent: function() { + return this.map( function() { + var offsetParent = this.offsetParent; + + while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) { + offsetParent = offsetParent.offsetParent; + } + + return offsetParent || documentElement; + } ); + } +} ); + +// Create scrollLeft and scrollTop methods +jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { + var top = "pageYOffset" === prop; + + jQuery.fn[ method ] = function( val ) { + return access( this, function( elem, method, val ) { + var win = getWindow( elem ); + + if ( val === undefined ) { + return win ? win[ prop ] : elem[ method ]; + } + + if ( win ) { + win.scrollTo( + !top ? val : win.pageXOffset, + top ? val : win.pageYOffset + ); + + } else { + elem[ method ] = val; + } + }, method, val, arguments.length ); + }; +} ); + +// Support: Safari<7-8+, Chrome<37-44+ +// Add the top/left cssHooks using jQuery.fn.position +// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 +// Blink bug: https://code.google.com/p/chromium/issues/detail?id=229280 +// getComputedStyle returns percent when specified for top/left/bottom/right; +// rather than make the css module depend on the offset module, just check for it here +jQuery.each( [ "top", "left" ], function( i, prop ) { + jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, + function( elem, computed ) { + if ( computed ) { + computed = curCSS( elem, prop ); + + // If curCSS returns percentage, fallback to offset + return rnumnonpx.test( computed ) ? + jQuery( elem ).position()[ prop ] + "px" : + computed; + } + } + ); +} ); + + +// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods +jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { + jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, + function( defaultExtra, funcName ) { + + // Margin is only for outerHeight, outerWidth + jQuery.fn[ funcName ] = function( margin, value ) { + var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), + extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); + + return access( this, function( elem, type, value ) { + var doc; + + if ( jQuery.isWindow( elem ) ) { + + // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there + // isn't a whole lot we can do. See pull request at this URL for discussion: + // https://github.com/jquery/jquery/pull/764 + return elem.document.documentElement[ "client" + name ]; + } + + // Get document width or height + if ( elem.nodeType === 9 ) { + doc = elem.documentElement; + + // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], + // whichever is greatest + return Math.max( + elem.body[ "scroll" + name ], doc[ "scroll" + name ], + elem.body[ "offset" + name ], doc[ "offset" + name ], + doc[ "client" + name ] + ); + } + + return value === undefined ? + + // Get width or height on the element, requesting but not forcing parseFloat + jQuery.css( elem, type, extra ) : + + // Set width or height on the element + jQuery.style( elem, type, value, extra ); + }, type, chainable ? margin : undefined, chainable, null ); + }; + } ); +} ); + + +jQuery.fn.extend( { + + bind: function( types, data, fn ) { + return this.on( types, null, data, fn ); + }, + unbind: function( types, fn ) { + return this.off( types, null, fn ); + }, + + delegate: function( selector, types, data, fn ) { + return this.on( types, selector, data, fn ); + }, + undelegate: function( selector, types, fn ) { + + // ( namespace ) or ( selector, types [, fn] ) + return arguments.length === 1 ? + this.off( selector, "**" ) : + this.off( types, selector || "**", fn ); + }, + size: function() { + return this.length; + } +} ); + +jQuery.fn.andSelf = jQuery.fn.addBack; + + + + +// Register as a named AMD module, since jQuery can be concatenated with other +// files that may use define, but not via a proper concatenation script that +// understands anonymous AMD modules. A named AMD is safest and most robust +// way to register. Lowercase jquery is used because AMD module names are +// derived from file names, and jQuery is normally delivered in a lowercase +// file name. Do this after creating the global so that if an AMD module wants +// to call noConflict to hide this version of jQuery, it will work. + +// Note that for maximum portability, libraries that are not jQuery should +// declare themselves as anonymous modules, and avoid setting a global if an +// AMD loader is present. jQuery is a special case. For more information, see +// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon + +if ( typeof define === "function" && define.amd ) { + define( "jquery", [], function() { + return jQuery; + } ); +} + + + +var + + // Map over jQuery in case of overwrite + _jQuery = window.jQuery, + + // Map over the $ in case of overwrite + _$ = window.$; + +jQuery.noConflict = function( deep ) { + if ( window.$ === jQuery ) { + window.$ = _$; + } + + if ( deep && window.jQuery === jQuery ) { + window.jQuery = _jQuery; + } + + return jQuery; +}; + +// Expose jQuery and $ identifiers, even in AMD +// (#7102#comment:10, https://github.com/jquery/jquery/pull/557) +// and CommonJS for browser emulators (#13566) +if ( !noGlobal ) { + window.jQuery = window.$ = jQuery; +} + +return jQuery; +})); diff --git a/actionview/test/ujs/public/vendor/jquery.metadata.js b/actionview/test/ujs/public/vendor/jquery.metadata.js new file mode 100644 index 0000000000..5b5253cdf7 --- /dev/null +++ b/actionview/test/ujs/public/vendor/jquery.metadata.js @@ -0,0 +1,122 @@ +/* + * Metadata - jQuery plugin for parsing metadata from elements + * + * Copyright (c) 2006 John Resig, Yehuda Katz, J�örn Zaefferer, Paul McLanahan + * + * Dual licensed under the MIT and GPL licenses: + * http://www.opensource.org/licenses/mit-license.php + * http://www.gnu.org/licenses/gpl.html + * + * Revision: $Id: jquery.metadata.js 4187 2007-12-16 17:15:27Z joern.zaefferer $ + * + */ + +/** + * Sets the type of metadata to use. Metadata is encoded in JSON, and each property + * in the JSON will become a property of the element itself. + * + * There are three supported types of metadata storage: + * + * attr: Inside an attribute. The name parameter indicates *which* attribute. + * + * class: Inside the class attribute, wrapped in curly braces: { } + * + * elem: Inside a child element (e.g. a script tag). The + * name parameter indicates *which* element. + * + * The metadata for an element is loaded the first time the element is accessed via jQuery. + * + * As a result, you can define the metadata type, use $(expr) to load the metadata into the elements + * matched by expr, then redefine the metadata type and run another $(expr) for other elements. + * + * @name $.metadata.setType + * + * @example <p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p> + * @before $.metadata.setType("class") + * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label" + * @desc Reads metadata from the class attribute + * + * @example <p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p> + * @before $.metadata.setType("attr", "data") + * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label" + * @desc Reads metadata from a "data" attribute + * + * @example <p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a p</p> + * @before $.metadata.setType("elem", "script") + * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label" + * @desc Reads metadata from a nested script element + * + * @param String type The encoding type + * @param String name The name of the attribute to be used to get metadata (optional) + * @cat Plugins/Metadata + * @descr Sets the type of encoding to be used when loading metadata for the first time + * @type undefined + * @see metadata() + */ + +(function($) { + +$.extend({ + metadata : { + defaults : { + type: 'class', + name: 'metadata', + cre: /({.*})/, + single: 'metadata' + }, + setType: function( type, name ){ + this.defaults.type = type; + this.defaults.name = name; + }, + get: function( elem, opts ){ + var settings = $.extend({},this.defaults,opts); + // check for empty string in single property + if ( !settings.single.length ) settings.single = 'metadata'; + + var data = $.data(elem, settings.single); + // returned cached data if it already exists + if ( data ) return data; + + data = "{}"; + + if ( settings.type == "class" ) { + var m = settings.cre.exec( elem.className ); + if ( m ) + data = m[1]; + } else if ( settings.type == "elem" ) { + if( !elem.getElementsByTagName ) + return undefined; + var e = elem.getElementsByTagName(settings.name); + if ( e.length ) + data = $.trim(e[0].innerHTML); + } else if ( elem.getAttribute != undefined ) { + var attr = elem.getAttribute( settings.name ); + if ( attr ) + data = attr; + } + + if ( data.indexOf( '{' ) <0 ) + data = "{" + data + "}"; + + data = eval("(" + data + ")"); + + $.data( elem, settings.single, data ); + return data; + } + } +}); + +/** + * Returns the metadata object for the first member of the jQuery object. + * + * @name metadata + * @descr Returns element's metadata object + * @param Object opts An object containing settings to override the defaults + * @type jQuery + * @cat Plugins/Metadata + */ +$.fn.metadata = function( opts ){ + return $.metadata.get( this[0], opts ); +}; + +})(jQuery);
\ No newline at end of file diff --git a/actionview/test/ujs/public/vendor/qunit.css b/actionview/test/ujs/public/vendor/qunit.css new file mode 100644 index 0000000000..93026e3ba3 --- /dev/null +++ b/actionview/test/ujs/public/vendor/qunit.css @@ -0,0 +1,237 @@ +/*! + * QUnit 1.14.0 + * http://qunitjs.com/ + * + * Copyright 2013 jQuery Foundation and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2014-01-31T16:40Z + */ + +/** Font Family and Sizes */ + +#qunit-tests, #qunit-header, #qunit-banner, #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult { + font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial, sans-serif; +} + +#qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult, #qunit-tests li { font-size: small; } +#qunit-tests { font-size: smaller; } + + +/** Resets */ + +#qunit-tests, #qunit-header, #qunit-banner, #qunit-userAgent, #qunit-testresult, #qunit-modulefilter { + margin: 0; + padding: 0; +} + + +/** Header */ + +#qunit-header { + padding: 0.5em 0 0.5em 1em; + + color: #8699A4; + background-color: #0D3349; + + font-size: 1.5em; + line-height: 1em; + font-weight: 400; + + border-radius: 5px 5px 0 0; +} + +#qunit-header a { + text-decoration: none; + color: #C2CCD1; +} + +#qunit-header a:hover, +#qunit-header a:focus { + color: #FFF; +} + +#qunit-testrunner-toolbar label { + display: inline-block; + padding: 0 0.5em 0 0.1em; +} + +#qunit-banner { + height: 5px; +} + +#qunit-testrunner-toolbar { + padding: 0.5em 0 0.5em 2em; + color: #5E740B; + background-color: #EEE; + overflow: hidden; +} + +#qunit-userAgent { + padding: 0.5em 0 0.5em 2.5em; + background-color: #2B81AF; + color: #FFF; + text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px; +} + +#qunit-modulefilter-container { + float: right; +} + +/** Tests: Pass/Fail */ + +#qunit-tests { + list-style-position: inside; +} + +#qunit-tests li { + padding: 0.4em 0.5em 0.4em 2.5em; + border-bottom: 1px solid #FFF; + list-style-position: inside; +} + +#qunit-tests.hidepass li.pass, #qunit-tests.hidepass li.running { + display: none; +} + +#qunit-tests li strong { + cursor: pointer; +} + +#qunit-tests li a { + padding: 0.5em; + color: #C2CCD1; + text-decoration: none; +} +#qunit-tests li a:hover, +#qunit-tests li a:focus { + color: #000; +} + +#qunit-tests li .runtime { + float: right; + font-size: smaller; +} + +.qunit-assert-list { + margin-top: 0.5em; + padding: 0.5em; + + background-color: #FFF; + + border-radius: 5px; +} + +.qunit-collapsed { + display: none; +} + +#qunit-tests table { + border-collapse: collapse; + margin-top: 0.2em; +} + +#qunit-tests th { + text-align: right; + vertical-align: top; + padding: 0 0.5em 0 0; +} + +#qunit-tests td { + vertical-align: top; +} + +#qunit-tests pre { + margin: 0; + white-space: pre-wrap; + word-wrap: break-word; +} + +#qunit-tests del { + background-color: #E0F2BE; + color: #374E0C; + text-decoration: none; +} + +#qunit-tests ins { + background-color: #FFCACA; + color: #500; + text-decoration: none; +} + +/*** Test Counts */ + +#qunit-tests b.counts { color: #000; } +#qunit-tests b.passed { color: #5E740B; } +#qunit-tests b.failed { color: #710909; } + +#qunit-tests li li { + padding: 5px; + background-color: #FFF; + border-bottom: none; + list-style-position: inside; +} + +/*** Passing Styles */ + +#qunit-tests li li.pass { + color: #3C510C; + background-color: #FFF; + border-left: 10px solid #C6E746; +} + +#qunit-tests .pass { color: #528CE0; background-color: #D2E0E6; } +#qunit-tests .pass .test-name { color: #366097; } + +#qunit-tests .pass .test-actual, +#qunit-tests .pass .test-expected { color: #999; } + +#qunit-banner.qunit-pass { background-color: #C6E746; } + +/*** Failing Styles */ + +#qunit-tests li li.fail { + color: #710909; + background-color: #FFF; + border-left: 10px solid #EE5757; + white-space: pre; +} + +#qunit-tests > li:last-child { + border-radius: 0 0 5px 5px; +} + +#qunit-tests .fail { color: #000; background-color: #EE5757; } +#qunit-tests .fail .test-name, +#qunit-tests .fail .module-name { color: #000; } + +#qunit-tests .fail .test-actual { color: #EE5757; } +#qunit-tests .fail .test-expected { color: #008000; } + +#qunit-banner.qunit-fail { background-color: #EE5757; } + + +/** Result */ + +#qunit-testresult { + padding: 0.5em 0.5em 0.5em 2.5em; + + color: #2B81AF; + background-color: #D2E0E6; + + border-bottom: 1px solid #FFF; +} +#qunit-testresult .module-name { + font-weight: 700; +} + +/** Fixture */ + +#qunit-fixture { + position: absolute; + top: -10000px; + left: -10000px; + width: 1000px; + height: 1000px; +} diff --git a/actionview/test/ujs/public/vendor/qunit.js b/actionview/test/ujs/public/vendor/qunit.js new file mode 100644 index 0000000000..50a9e6455d --- /dev/null +++ b/actionview/test/ujs/public/vendor/qunit.js @@ -0,0 +1,2288 @@ +/*! + * QUnit 1.14.0 + * http://qunitjs.com/ + * + * Copyright 2013 jQuery Foundation and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2014-01-31T16:40Z + */ + +(function( window ) { + +var QUnit, + assert, + config, + onErrorFnPrev, + testId = 0, + fileName = (sourceFromStacktrace( 0 ) || "" ).replace(/(:\d+)+\)?/, "").replace(/.+\//, ""), + toString = Object.prototype.toString, + hasOwn = Object.prototype.hasOwnProperty, + // Keep a local reference to Date (GH-283) + Date = window.Date, + setTimeout = window.setTimeout, + clearTimeout = window.clearTimeout, + defined = { + document: typeof window.document !== "undefined", + setTimeout: typeof window.setTimeout !== "undefined", + sessionStorage: (function() { + var x = "qunit-test-string"; + try { + sessionStorage.setItem( x, x ); + sessionStorage.removeItem( x ); + return true; + } catch( e ) { + return false; + } + }()) + }, + /** + * Provides a normalized error string, correcting an issue + * with IE 7 (and prior) where Error.prototype.toString is + * not properly implemented + * + * Based on https://es5.github.io/#x15.11.4.4 + * + * @param {String|Error} error + * @return {String} error message + */ + errorString = function( error ) { + var name, message, + errorString = error.toString(); + if ( errorString.substring( 0, 7 ) === "[object" ) { + name = error.name ? error.name.toString() : "Error"; + message = error.message ? error.message.toString() : ""; + if ( name && message ) { + return name + ": " + message; + } else if ( name ) { + return name; + } else if ( message ) { + return message; + } else { + return "Error"; + } + } else { + return errorString; + } + }, + /** + * Makes a clone of an object using only Array or Object as base, + * and copies over the own enumerable properties. + * + * @param {Object} obj + * @return {Object} New object with only the own properties (recursively). + */ + objectValues = function( obj ) { + // Grunt 0.3.x uses an older version of jshint that still has jshint/jshint#392. + /*jshint newcap: false */ + var key, val, + vals = QUnit.is( "array", obj ) ? [] : {}; + for ( key in obj ) { + if ( hasOwn.call( obj, key ) ) { + val = obj[key]; + vals[key] = val === Object(val) ? objectValues(val) : val; + } + } + return vals; + }; + + +// Root QUnit object. +// `QUnit` initialized at top of scope +QUnit = { + + // call on start of module test to prepend name to all tests + module: function( name, testEnvironment ) { + config.currentModule = name; + config.currentModuleTestEnvironment = testEnvironment; + config.modules[name] = true; + }, + + asyncTest: function( testName, expected, callback ) { + if ( arguments.length === 2 ) { + callback = expected; + expected = null; + } + + QUnit.test( testName, expected, callback, true ); + }, + + test: function( testName, expected, callback, async ) { + var test, + nameHtml = "<span class='test-name'>" + escapeText( testName ) + "</span>"; + + if ( arguments.length === 2 ) { + callback = expected; + expected = null; + } + + if ( config.currentModule ) { + nameHtml = "<span class='module-name'>" + escapeText( config.currentModule ) + "</span>: " + nameHtml; + } + + test = new Test({ + nameHtml: nameHtml, + testName: testName, + expected: expected, + async: async, + callback: callback, + module: config.currentModule, + moduleTestEnvironment: config.currentModuleTestEnvironment, + stack: sourceFromStacktrace( 2 ) + }); + + if ( !validTest( test ) ) { + return; + } + + test.queue(); + }, + + // Specify the number of expected assertions to guarantee that failed test (no assertions are run at all) don't slip through. + expect: function( asserts ) { + if (arguments.length === 1) { + config.current.expected = asserts; + } else { + return config.current.expected; + } + }, + + start: function( count ) { + // QUnit hasn't been initialized yet. + // Note: RequireJS (et al) may delay onLoad + if ( config.semaphore === undefined ) { + QUnit.begin(function() { + // This is triggered at the top of QUnit.load, push start() to the event loop, to allow QUnit.load to finish first + setTimeout(function() { + QUnit.start( count ); + }); + }); + return; + } + + config.semaphore -= count || 1; + // don't start until equal number of stop-calls + if ( config.semaphore > 0 ) { + return; + } + // ignore if start is called more often then stop + if ( config.semaphore < 0 ) { + config.semaphore = 0; + QUnit.pushFailure( "Called start() while already started (QUnit.config.semaphore was 0 already)", null, sourceFromStacktrace(2) ); + return; + } + // A slight delay, to avoid any current callbacks + if ( defined.setTimeout ) { + setTimeout(function() { + if ( config.semaphore > 0 ) { + return; + } + if ( config.timeout ) { + clearTimeout( config.timeout ); + } + + config.blocking = false; + process( true ); + }, 13); + } else { + config.blocking = false; + process( true ); + } + }, + + stop: function( count ) { + config.semaphore += count || 1; + config.blocking = true; + + if ( config.testTimeout && defined.setTimeout ) { + clearTimeout( config.timeout ); + config.timeout = setTimeout(function() { + QUnit.ok( false, "Test timed out" ); + config.semaphore = 1; + QUnit.start(); + }, config.testTimeout ); + } + } +}; + +// We use the prototype to distinguish between properties that should +// be exposed as globals (and in exports) and those that shouldn't +(function() { + function F() {} + F.prototype = QUnit; + QUnit = new F(); + // Make F QUnit's constructor so that we can add to the prototype later + QUnit.constructor = F; +}()); + +/** + * Config object: Maintain internal state + * Later exposed as QUnit.config + * `config` initialized at top of scope + */ +config = { + // The queue of tests to run + queue: [], + + // block until document ready + blocking: true, + + // when enabled, show only failing tests + // gets persisted through sessionStorage and can be changed in UI via checkbox + hidepassed: false, + + // by default, run previously failed tests first + // very useful in combination with "Hide passed tests" checked + reorder: true, + + // by default, modify document.title when suite is done + altertitle: true, + + // by default, scroll to top of the page when suite is done + scrolltop: true, + + // when enabled, all tests must call expect() + requireExpects: false, + + // add checkboxes that are persisted in the query-string + // when enabled, the id is set to `true` as a `QUnit.config` property + urlConfig: [ + { + id: "noglobals", + label: "Check for Globals", + tooltip: "Enabling this will test if any test introduces new properties on the `window` object. Stored as query-strings." + }, + { + id: "notrycatch", + label: "No try-catch", + tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging exceptions in IE reasonable. Stored as query-strings." + } + ], + + // Set of all modules. + modules: {}, + + // logging callback queues + begin: [], + done: [], + log: [], + testStart: [], + testDone: [], + moduleStart: [], + moduleDone: [] +}; + +// Initialize more QUnit.config and QUnit.urlParams +(function() { + var i, current, + location = window.location || { search: "", protocol: "file:" }, + params = location.search.slice( 1 ).split( "&" ), + length = params.length, + urlParams = {}; + + if ( params[ 0 ] ) { + for ( i = 0; i < length; i++ ) { + current = params[ i ].split( "=" ); + current[ 0 ] = decodeURIComponent( current[ 0 ] ); + + // allow just a key to turn on a flag, e.g., test.html?noglobals + current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true; + if ( urlParams[ current[ 0 ] ] ) { + urlParams[ current[ 0 ] ] = [].concat( urlParams[ current[ 0 ] ], current[ 1 ] ); + } else { + urlParams[ current[ 0 ] ] = current[ 1 ]; + } + } + } + + QUnit.urlParams = urlParams; + + // String search anywhere in moduleName+testName + config.filter = urlParams.filter; + + // Exact match of the module name + config.module = urlParams.module; + + config.testNumber = []; + if ( urlParams.testNumber ) { + + // Ensure that urlParams.testNumber is an array + urlParams.testNumber = [].concat( urlParams.testNumber ); + for ( i = 0; i < urlParams.testNumber.length; i++ ) { + current = urlParams.testNumber[ i ]; + config.testNumber.push( parseInt( current, 10 ) ); + } + } + + // Figure out if we're running the tests from a server or not + QUnit.isLocal = location.protocol === "file:"; +}()); + +extend( QUnit, { + + config: config, + + // Initialize the configuration options + init: function() { + extend( config, { + stats: { all: 0, bad: 0 }, + moduleStats: { all: 0, bad: 0 }, + started: +new Date(), + updateRate: 1000, + blocking: false, + autostart: true, + autorun: false, + filter: "", + queue: [], + semaphore: 1 + }); + + var tests, banner, result, + qunit = id( "qunit" ); + + if ( qunit ) { + qunit.innerHTML = + "<h1 id='qunit-header'>" + escapeText( document.title ) + "</h1>" + + "<h2 id='qunit-banner'></h2>" + + "<div id='qunit-testrunner-toolbar'></div>" + + "<h2 id='qunit-userAgent'></h2>" + + "<ol id='qunit-tests'></ol>"; + } + + tests = id( "qunit-tests" ); + banner = id( "qunit-banner" ); + result = id( "qunit-testresult" ); + + if ( tests ) { + tests.innerHTML = ""; + } + + if ( banner ) { + banner.className = ""; + } + + if ( result ) { + result.parentNode.removeChild( result ); + } + + if ( tests ) { + result = document.createElement( "p" ); + result.id = "qunit-testresult"; + result.className = "result"; + tests.parentNode.insertBefore( result, tests ); + result.innerHTML = "Running...<br/> "; + } + }, + + // Resets the test setup. Useful for tests that modify the DOM. + /* + DEPRECATED: Use multiple tests instead of resetting inside a test. + Use testStart or testDone for custom cleanup. + This method will throw an error in 2.0, and will be removed in 2.1 + */ + reset: function() { + var fixture = id( "qunit-fixture" ); + if ( fixture ) { + fixture.innerHTML = config.fixture; + } + }, + + // Safe object type checking + is: function( type, obj ) { + return QUnit.objectType( obj ) === type; + }, + + objectType: function( obj ) { + if ( typeof obj === "undefined" ) { + return "undefined"; + } + + // Consider: typeof null === object + if ( obj === null ) { + return "null"; + } + + var match = toString.call( obj ).match(/^\[object\s(.*)\]$/), + type = match && match[1] || ""; + + switch ( type ) { + case "Number": + if ( isNaN(obj) ) { + return "nan"; + } + return "number"; + case "String": + case "Boolean": + case "Array": + case "Date": + case "RegExp": + case "Function": + return type.toLowerCase(); + } + if ( typeof obj === "object" ) { + return "object"; + } + return undefined; + }, + + push: function( result, actual, expected, message ) { + if ( !config.current ) { + throw new Error( "assertion outside test context, was " + sourceFromStacktrace() ); + } + + var output, source, + details = { + module: config.current.module, + name: config.current.testName, + result: result, + message: message, + actual: actual, + expected: expected + }; + + message = escapeText( message ) || ( result ? "okay" : "failed" ); + message = "<span class='test-message'>" + message + "</span>"; + output = message; + + if ( !result ) { + expected = escapeText( QUnit.jsDump.parse(expected) ); + actual = escapeText( QUnit.jsDump.parse(actual) ); + output += "<table><tr class='test-expected'><th>Expected: </th><td><pre>" + expected + "</pre></td></tr>"; + + if ( actual !== expected ) { + output += "<tr class='test-actual'><th>Result: </th><td><pre>" + actual + "</pre></td></tr>"; + output += "<tr class='test-diff'><th>Diff: </th><td><pre>" + QUnit.diff( expected, actual ) + "</pre></td></tr>"; + } + + source = sourceFromStacktrace(); + + if ( source ) { + details.source = source; + output += "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText( source ) + "</pre></td></tr>"; + } + + output += "</table>"; + } + + runLoggingCallbacks( "log", QUnit, details ); + + config.current.assertions.push({ + result: !!result, + message: output + }); + }, + + pushFailure: function( message, source, actual ) { + if ( !config.current ) { + throw new Error( "pushFailure() assertion outside test context, was " + sourceFromStacktrace(2) ); + } + + var output, + details = { + module: config.current.module, + name: config.current.testName, + result: false, + message: message + }; + + message = escapeText( message ) || "error"; + message = "<span class='test-message'>" + message + "</span>"; + output = message; + + output += "<table>"; + + if ( actual ) { + output += "<tr class='test-actual'><th>Result: </th><td><pre>" + escapeText( actual ) + "</pre></td></tr>"; + } + + if ( source ) { + details.source = source; + output += "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText( source ) + "</pre></td></tr>"; + } + + output += "</table>"; + + runLoggingCallbacks( "log", QUnit, details ); + + config.current.assertions.push({ + result: false, + message: output + }); + }, + + url: function( params ) { + params = extend( extend( {}, QUnit.urlParams ), params ); + var key, + querystring = "?"; + + for ( key in params ) { + if ( hasOwn.call( params, key ) ) { + querystring += encodeURIComponent( key ) + "=" + + encodeURIComponent( params[ key ] ) + "&"; + } + } + return window.location.protocol + "//" + window.location.host + + window.location.pathname + querystring.slice( 0, -1 ); + }, + + extend: extend, + id: id, + addEvent: addEvent, + addClass: addClass, + hasClass: hasClass, + removeClass: removeClass + // load, equiv, jsDump, diff: Attached later +}); + +/** + * @deprecated: Created for backwards compatibility with test runner that set the hook function + * into QUnit.{hook}, instead of invoking it and passing the hook function. + * QUnit.constructor is set to the empty F() above so that we can add to it's prototype here. + * Doing this allows us to tell if the following methods have been overwritten on the actual + * QUnit object. + */ +extend( QUnit.constructor.prototype, { + + // Logging callbacks; all receive a single argument with the listed properties + // run test/logs.html for any related changes + begin: registerLoggingCallback( "begin" ), + + // done: { failed, passed, total, runtime } + done: registerLoggingCallback( "done" ), + + // log: { result, actual, expected, message } + log: registerLoggingCallback( "log" ), + + // testStart: { name } + testStart: registerLoggingCallback( "testStart" ), + + // testDone: { name, failed, passed, total, runtime } + testDone: registerLoggingCallback( "testDone" ), + + // moduleStart: { name } + moduleStart: registerLoggingCallback( "moduleStart" ), + + // moduleDone: { name, failed, passed, total } + moduleDone: registerLoggingCallback( "moduleDone" ) +}); + +if ( !defined.document || document.readyState === "complete" ) { + config.autorun = true; +} + +QUnit.load = function() { + runLoggingCallbacks( "begin", QUnit, {} ); + + // Initialize the config, saving the execution queue + var banner, filter, i, j, label, len, main, ol, toolbar, val, selection, + urlConfigContainer, moduleFilter, userAgent, + numModules = 0, + moduleNames = [], + moduleFilterHtml = "", + urlConfigHtml = "", + oldconfig = extend( {}, config ); + + QUnit.init(); + extend(config, oldconfig); + + config.blocking = false; + + len = config.urlConfig.length; + + for ( i = 0; i < len; i++ ) { + val = config.urlConfig[i]; + if ( typeof val === "string" ) { + val = { + id: val, + label: val + }; + } + config[ val.id ] = QUnit.urlParams[ val.id ]; + if ( !val.value || typeof val.value === "string" ) { + urlConfigHtml += "<input id='qunit-urlconfig-" + escapeText( val.id ) + + "' name='" + escapeText( val.id ) + + "' type='checkbox'" + + ( val.value ? " value='" + escapeText( val.value ) + "'" : "" ) + + ( config[ val.id ] ? " checked='checked'" : "" ) + + " title='" + escapeText( val.tooltip ) + + "'><label for='qunit-urlconfig-" + escapeText( val.id ) + + "' title='" + escapeText( val.tooltip ) + "'>" + val.label + "</label>"; + } else { + urlConfigHtml += "<label for='qunit-urlconfig-" + escapeText( val.id ) + + "' title='" + escapeText( val.tooltip ) + + "'>" + val.label + + ": </label><select id='qunit-urlconfig-" + escapeText( val.id ) + + "' name='" + escapeText( val.id ) + + "' title='" + escapeText( val.tooltip ) + + "'><option></option>"; + selection = false; + if ( QUnit.is( "array", val.value ) ) { + for ( j = 0; j < val.value.length; j++ ) { + urlConfigHtml += "<option value='" + escapeText( val.value[j] ) + "'" + + ( config[ val.id ] === val.value[j] ? + (selection = true) && " selected='selected'" : + "" ) + + ">" + escapeText( val.value[j] ) + "</option>"; + } + } else { + for ( j in val.value ) { + if ( hasOwn.call( val.value, j ) ) { + urlConfigHtml += "<option value='" + escapeText( j ) + "'" + + ( config[ val.id ] === j ? + (selection = true) && " selected='selected'" : + "" ) + + ">" + escapeText( val.value[j] ) + "</option>"; + } + } + } + if ( config[ val.id ] && !selection ) { + urlConfigHtml += "<option value='" + escapeText( config[ val.id ] ) + + "' selected='selected' disabled='disabled'>" + + escapeText( config[ val.id ] ) + + "</option>"; + } + urlConfigHtml += "</select>"; + } + } + for ( i in config.modules ) { + if ( config.modules.hasOwnProperty( i ) ) { + moduleNames.push(i); + } + } + numModules = moduleNames.length; + moduleNames.sort( function( a, b ) { + return a.localeCompare( b ); + }); + moduleFilterHtml += "<label for='qunit-modulefilter'>Module: </label><select id='qunit-modulefilter' name='modulefilter'><option value='' " + + ( config.module === undefined ? "selected='selected'" : "" ) + + ">< All Modules ></option>"; + + + for ( i = 0; i < numModules; i++) { + moduleFilterHtml += "<option value='" + escapeText( encodeURIComponent(moduleNames[i]) ) + "' " + + ( config.module === moduleNames[i] ? "selected='selected'" : "" ) + + ">" + escapeText(moduleNames[i]) + "</option>"; + } + moduleFilterHtml += "</select>"; + + // `userAgent` initialized at top of scope + userAgent = id( "qunit-userAgent" ); + if ( userAgent ) { + userAgent.innerHTML = navigator.userAgent; + } + + // `banner` initialized at top of scope + banner = id( "qunit-header" ); + if ( banner ) { + banner.innerHTML = "<a href='" + QUnit.url({ filter: undefined, module: undefined, testNumber: undefined }) + "'>" + banner.innerHTML + "</a> "; + } + + // `toolbar` initialized at top of scope + toolbar = id( "qunit-testrunner-toolbar" ); + if ( toolbar ) { + // `filter` initialized at top of scope + filter = document.createElement( "input" ); + filter.type = "checkbox"; + filter.id = "qunit-filter-pass"; + + addEvent( filter, "click", function() { + var tmp, + ol = id( "qunit-tests" ); + + if ( filter.checked ) { + ol.className = ol.className + " hidepass"; + } else { + tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " "; + ol.className = tmp.replace( / hidepass /, " " ); + } + if ( defined.sessionStorage ) { + if (filter.checked) { + sessionStorage.setItem( "qunit-filter-passed-tests", "true" ); + } else { + sessionStorage.removeItem( "qunit-filter-passed-tests" ); + } + } + }); + + if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem( "qunit-filter-passed-tests" ) ) { + filter.checked = true; + // `ol` initialized at top of scope + ol = id( "qunit-tests" ); + ol.className = ol.className + " hidepass"; + } + toolbar.appendChild( filter ); + + // `label` initialized at top of scope + label = document.createElement( "label" ); + label.setAttribute( "for", "qunit-filter-pass" ); + label.setAttribute( "title", "Only show tests and assertions that fail. Stored in sessionStorage." ); + label.innerHTML = "Hide passed tests"; + toolbar.appendChild( label ); + + urlConfigContainer = document.createElement("span"); + urlConfigContainer.innerHTML = urlConfigHtml; + // For oldIE support: + // * Add handlers to the individual elements instead of the container + // * Use "click" instead of "change" for checkboxes + // * Fallback from event.target to event.srcElement + addEvents( urlConfigContainer.getElementsByTagName("input"), "click", function( event ) { + var params = {}, + target = event.target || event.srcElement; + params[ target.name ] = target.checked ? + target.defaultValue || true : + undefined; + window.location = QUnit.url( params ); + }); + addEvents( urlConfigContainer.getElementsByTagName("select"), "change", function( event ) { + var params = {}, + target = event.target || event.srcElement; + params[ target.name ] = target.options[ target.selectedIndex ].value || undefined; + window.location = QUnit.url( params ); + }); + toolbar.appendChild( urlConfigContainer ); + + if (numModules > 1) { + moduleFilter = document.createElement( "span" ); + moduleFilter.setAttribute( "id", "qunit-modulefilter-container" ); + moduleFilter.innerHTML = moduleFilterHtml; + addEvent( moduleFilter.lastChild, "change", function() { + var selectBox = moduleFilter.getElementsByTagName("select")[0], + selectedModule = decodeURIComponent(selectBox.options[selectBox.selectedIndex].value); + + window.location = QUnit.url({ + module: ( selectedModule === "" ) ? undefined : selectedModule, + // Remove any existing filters + filter: undefined, + testNumber: undefined + }); + }); + toolbar.appendChild(moduleFilter); + } + } + + // `main` initialized at top of scope + main = id( "qunit-fixture" ); + if ( main ) { + config.fixture = main.innerHTML; + } + + if ( config.autostart ) { + QUnit.start(); + } +}; + +if ( defined.document ) { + addEvent( window, "load", QUnit.load ); +} + +// `onErrorFnPrev` initialized at top of scope +// Preserve other handlers +onErrorFnPrev = window.onerror; + +// Cover uncaught exceptions +// Returning true will suppress the default browser handler, +// returning false will let it run. +window.onerror = function ( error, filePath, linerNr ) { + var ret = false; + if ( onErrorFnPrev ) { + ret = onErrorFnPrev( error, filePath, linerNr ); + } + + // Treat return value as window.onerror itself does, + // Only do our handling if not suppressed. + if ( ret !== true ) { + if ( QUnit.config.current ) { + if ( QUnit.config.current.ignoreGlobalErrors ) { + return true; + } + QUnit.pushFailure( error, filePath + ":" + linerNr ); + } else { + QUnit.test( "global failure", extend( function() { + QUnit.pushFailure( error, filePath + ":" + linerNr ); + }, { validTest: validTest } ) ); + } + return false; + } + + return ret; +}; + +function done() { + config.autorun = true; + + // Log the last module results + if ( config.previousModule ) { + runLoggingCallbacks( "moduleDone", QUnit, { + name: config.previousModule, + failed: config.moduleStats.bad, + passed: config.moduleStats.all - config.moduleStats.bad, + total: config.moduleStats.all + }); + } + delete config.previousModule; + + var i, key, + banner = id( "qunit-banner" ), + tests = id( "qunit-tests" ), + runtime = +new Date() - config.started, + passed = config.stats.all - config.stats.bad, + html = [ + "Tests completed in ", + runtime, + " milliseconds.<br/>", + "<span class='passed'>", + passed, + "</span> assertions of <span class='total'>", + config.stats.all, + "</span> passed, <span class='failed'>", + config.stats.bad, + "</span> failed." + ].join( "" ); + + if ( banner ) { + banner.className = ( config.stats.bad ? "qunit-fail" : "qunit-pass" ); + } + + if ( tests ) { + id( "qunit-testresult" ).innerHTML = html; + } + + if ( config.altertitle && defined.document && document.title ) { + // show ✖ for good, ✔ for bad suite result in title + // use escape sequences in case file gets loaded with non-utf-8-charset + document.title = [ + ( config.stats.bad ? "\u2716" : "\u2714" ), + document.title.replace( /^[\u2714\u2716] /i, "" ) + ].join( " " ); + } + + // clear own sessionStorage items if all tests passed + if ( config.reorder && defined.sessionStorage && config.stats.bad === 0 ) { + // `key` & `i` initialized at top of scope + for ( i = 0; i < sessionStorage.length; i++ ) { + key = sessionStorage.key( i++ ); + if ( key.indexOf( "qunit-test-" ) === 0 ) { + sessionStorage.removeItem( key ); + } + } + } + + // scroll back to top to show results + if ( config.scrolltop && window.scrollTo ) { + window.scrollTo(0, 0); + } + + runLoggingCallbacks( "done", QUnit, { + failed: config.stats.bad, + passed: passed, + total: config.stats.all, + runtime: runtime + }); +} + +/** @return Boolean: true if this test should be ran */ +function validTest( test ) { + var include, + filter = config.filter && config.filter.toLowerCase(), + module = config.module && config.module.toLowerCase(), + fullName = ( test.module + ": " + test.testName ).toLowerCase(); + + // Internally-generated tests are always valid + if ( test.callback && test.callback.validTest === validTest ) { + delete test.callback.validTest; + return true; + } + + if ( config.testNumber.length > 0 ) { + if ( inArray( test.testNumber, config.testNumber ) < 0 ) { + return false; + } + } + + if ( module && ( !test.module || test.module.toLowerCase() !== module ) ) { + return false; + } + + if ( !filter ) { + return true; + } + + include = filter.charAt( 0 ) !== "!"; + if ( !include ) { + filter = filter.slice( 1 ); + } + + // If the filter matches, we need to honour include + if ( fullName.indexOf( filter ) !== -1 ) { + return include; + } + + // Otherwise, do the opposite + return !include; +} + +// so far supports only Firefox, Chrome and Opera (buggy), Safari (for real exceptions) +// Later Safari and IE10 are supposed to support error.stack as well +// See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack +function extractStacktrace( e, offset ) { + offset = offset === undefined ? 3 : offset; + + var stack, include, i; + + if ( e.stacktrace ) { + // Opera + return e.stacktrace.split( "\n" )[ offset + 3 ]; + } else if ( e.stack ) { + // Firefox, Chrome + stack = e.stack.split( "\n" ); + if (/^error$/i.test( stack[0] ) ) { + stack.shift(); + } + if ( fileName ) { + include = []; + for ( i = offset; i < stack.length; i++ ) { + if ( stack[ i ].indexOf( fileName ) !== -1 ) { + break; + } + include.push( stack[ i ] ); + } + if ( include.length ) { + return include.join( "\n" ); + } + } + return stack[ offset ]; + } else if ( e.sourceURL ) { + // Safari, PhantomJS + // hopefully one day Safari provides actual stacktraces + // exclude useless self-reference for generated Error objects + if ( /qunit.js$/.test( e.sourceURL ) ) { + return; + } + // for actual exceptions, this is useful + return e.sourceURL + ":" + e.line; + } +} +function sourceFromStacktrace( offset ) { + try { + throw new Error(); + } catch ( e ) { + return extractStacktrace( e, offset ); + } +} + +/** + * Escape text for attribute or text content. + */ +function escapeText( s ) { + if ( !s ) { + return ""; + } + s = s + ""; + // Both single quotes and double quotes (for attributes) + return s.replace( /['"<>&]/g, function( s ) { + switch( s ) { + case "'": + return "'"; + case "\"": + return """; + case "<": + return "<"; + case ">": + return ">"; + case "&": + return "&"; + } + }); +} + +function synchronize( callback, last ) { + config.queue.push( callback ); + + if ( config.autorun && !config.blocking ) { + process( last ); + } +} + +function process( last ) { + function next() { + process( last ); + } + var start = new Date().getTime(); + config.depth = config.depth ? config.depth + 1 : 1; + + while ( config.queue.length && !config.blocking ) { + if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) { + config.queue.shift()(); + } else { + setTimeout( next, 13 ); + break; + } + } + config.depth--; + if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) { + done(); + } +} + +function saveGlobal() { + config.pollution = []; + + if ( config.noglobals ) { + for ( var key in window ) { + if ( hasOwn.call( window, key ) ) { + // in Opera sometimes DOM element ids show up here, ignore them + if ( /^qunit-test-output/.test( key ) ) { + continue; + } + config.pollution.push( key ); + } + } + } +} + +function checkPollution() { + var newGlobals, + deletedGlobals, + old = config.pollution; + + saveGlobal(); + + newGlobals = diff( config.pollution, old ); + if ( newGlobals.length > 0 ) { + QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join(", ") ); + } + + deletedGlobals = diff( old, config.pollution ); + if ( deletedGlobals.length > 0 ) { + QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join(", ") ); + } +} + +// returns a new Array with the elements that are in a but not in b +function diff( a, b ) { + var i, j, + result = a.slice(); + + for ( i = 0; i < result.length; i++ ) { + for ( j = 0; j < b.length; j++ ) { + if ( result[i] === b[j] ) { + result.splice( i, 1 ); + i--; + break; + } + } + } + return result; +} + +function extend( a, b ) { + for ( var prop in b ) { + if ( hasOwn.call( b, prop ) ) { + // Avoid "Member not found" error in IE8 caused by messing with window.constructor + if ( !( prop === "constructor" && a === window ) ) { + if ( b[ prop ] === undefined ) { + delete a[ prop ]; + } else { + a[ prop ] = b[ prop ]; + } + } + } + } + + return a; +} + +/** + * @param {HTMLElement} elem + * @param {string} type + * @param {Function} fn + */ +function addEvent( elem, type, fn ) { + if ( elem.addEventListener ) { + + // Standards-based browsers + elem.addEventListener( type, fn, false ); + } else if ( elem.attachEvent ) { + + // support: IE <9 + elem.attachEvent( "on" + type, fn ); + } else { + + // Caller must ensure support for event listeners is present + throw new Error( "addEvent() was called in a context without event listener support" ); + } +} + +/** + * @param {Array|NodeList} elems + * @param {string} type + * @param {Function} fn + */ +function addEvents( elems, type, fn ) { + var i = elems.length; + while ( i-- ) { + addEvent( elems[i], type, fn ); + } +} + +function hasClass( elem, name ) { + return (" " + elem.className + " ").indexOf(" " + name + " ") > -1; +} + +function addClass( elem, name ) { + if ( !hasClass( elem, name ) ) { + elem.className += (elem.className ? " " : "") + name; + } +} + +function removeClass( elem, name ) { + var set = " " + elem.className + " "; + // Class name may appear multiple times + while ( set.indexOf(" " + name + " ") > -1 ) { + set = set.replace(" " + name + " " , " "); + } + // If possible, trim it for prettiness, but not necessarily + elem.className = typeof set.trim === "function" ? set.trim() : set.replace(/^\s+|\s+$/g, ""); +} + +function id( name ) { + return defined.document && document.getElementById && document.getElementById( name ); +} + +function registerLoggingCallback( key ) { + return function( callback ) { + config[key].push( callback ); + }; +} + +// Supports deprecated method of completely overwriting logging callbacks +function runLoggingCallbacks( key, scope, args ) { + var i, callbacks; + if ( QUnit.hasOwnProperty( key ) ) { + QUnit[ key ].call(scope, args ); + } else { + callbacks = config[ key ]; + for ( i = 0; i < callbacks.length; i++ ) { + callbacks[ i ].call( scope, args ); + } + } +} + +// from jquery.js +function inArray( elem, array ) { + if ( array.indexOf ) { + return array.indexOf( elem ); + } + + for ( var i = 0, length = array.length; i < length; i++ ) { + if ( array[ i ] === elem ) { + return i; + } + } + + return -1; +} + +function Test( settings ) { + extend( this, settings ); + this.assertions = []; + this.testNumber = ++Test.count; +} + +Test.count = 0; + +Test.prototype = { + init: function() { + var a, b, li, + tests = id( "qunit-tests" ); + + if ( tests ) { + b = document.createElement( "strong" ); + b.innerHTML = this.nameHtml; + + // `a` initialized at top of scope + a = document.createElement( "a" ); + a.innerHTML = "Rerun"; + a.href = QUnit.url({ testNumber: this.testNumber }); + + li = document.createElement( "li" ); + li.appendChild( b ); + li.appendChild( a ); + li.className = "running"; + li.id = this.id = "qunit-test-output" + testId++; + + tests.appendChild( li ); + } + }, + setup: function() { + if ( + // Emit moduleStart when we're switching from one module to another + this.module !== config.previousModule || + // They could be equal (both undefined) but if the previousModule property doesn't + // yet exist it means this is the first test in a suite that isn't wrapped in a + // module, in which case we'll just emit a moduleStart event for 'undefined'. + // Without this, reporters can get testStart before moduleStart which is a problem. + !hasOwn.call( config, "previousModule" ) + ) { + if ( hasOwn.call( config, "previousModule" ) ) { + runLoggingCallbacks( "moduleDone", QUnit, { + name: config.previousModule, + failed: config.moduleStats.bad, + passed: config.moduleStats.all - config.moduleStats.bad, + total: config.moduleStats.all + }); + } + config.previousModule = this.module; + config.moduleStats = { all: 0, bad: 0 }; + runLoggingCallbacks( "moduleStart", QUnit, { + name: this.module + }); + } + + config.current = this; + + this.testEnvironment = extend({ + setup: function() {}, + teardown: function() {} + }, this.moduleTestEnvironment ); + + this.started = +new Date(); + runLoggingCallbacks( "testStart", QUnit, { + name: this.testName, + module: this.module + }); + + /*jshint camelcase:false */ + + + /** + * Expose the current test environment. + * + * @deprecated since 1.12.0: Use QUnit.config.current.testEnvironment instead. + */ + QUnit.current_testEnvironment = this.testEnvironment; + + /*jshint camelcase:true */ + + if ( !config.pollution ) { + saveGlobal(); + } + if ( config.notrycatch ) { + this.testEnvironment.setup.call( this.testEnvironment, QUnit.assert ); + return; + } + try { + this.testEnvironment.setup.call( this.testEnvironment, QUnit.assert ); + } catch( e ) { + QUnit.pushFailure( "Setup failed on " + this.testName + ": " + ( e.message || e ), extractStacktrace( e, 1 ) ); + } + }, + run: function() { + config.current = this; + + var running = id( "qunit-testresult" ); + + if ( running ) { + running.innerHTML = "Running: <br/>" + this.nameHtml; + } + + if ( this.async ) { + QUnit.stop(); + } + + this.callbackStarted = +new Date(); + + if ( config.notrycatch ) { + this.callback.call( this.testEnvironment, QUnit.assert ); + this.callbackRuntime = +new Date() - this.callbackStarted; + return; + } + + try { + this.callback.call( this.testEnvironment, QUnit.assert ); + this.callbackRuntime = +new Date() - this.callbackStarted; + } catch( e ) { + this.callbackRuntime = +new Date() - this.callbackStarted; + + QUnit.pushFailure( "Died on test #" + (this.assertions.length + 1) + " " + this.stack + ": " + ( e.message || e ), extractStacktrace( e, 0 ) ); + // else next test will carry the responsibility + saveGlobal(); + + // Restart the tests if they're blocking + if ( config.blocking ) { + QUnit.start(); + } + } + }, + teardown: function() { + config.current = this; + if ( config.notrycatch ) { + if ( typeof this.callbackRuntime === "undefined" ) { + this.callbackRuntime = +new Date() - this.callbackStarted; + } + this.testEnvironment.teardown.call( this.testEnvironment, QUnit.assert ); + return; + } else { + try { + this.testEnvironment.teardown.call( this.testEnvironment, QUnit.assert ); + } catch( e ) { + QUnit.pushFailure( "Teardown failed on " + this.testName + ": " + ( e.message || e ), extractStacktrace( e, 1 ) ); + } + } + checkPollution(); + }, + finish: function() { + config.current = this; + if ( config.requireExpects && this.expected === null ) { + QUnit.pushFailure( "Expected number of assertions to be defined, but expect() was not called.", this.stack ); + } else if ( this.expected !== null && this.expected !== this.assertions.length ) { + QUnit.pushFailure( "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack ); + } else if ( this.expected === null && !this.assertions.length ) { + QUnit.pushFailure( "Expected at least one assertion, but none were run - call expect(0) to accept zero assertions.", this.stack ); + } + + var i, assertion, a, b, time, li, ol, + test = this, + good = 0, + bad = 0, + tests = id( "qunit-tests" ); + + this.runtime = +new Date() - this.started; + config.stats.all += this.assertions.length; + config.moduleStats.all += this.assertions.length; + + if ( tests ) { + ol = document.createElement( "ol" ); + ol.className = "qunit-assert-list"; + + for ( i = 0; i < this.assertions.length; i++ ) { + assertion = this.assertions[i]; + + li = document.createElement( "li" ); + li.className = assertion.result ? "pass" : "fail"; + li.innerHTML = assertion.message || ( assertion.result ? "okay" : "failed" ); + ol.appendChild( li ); + + if ( assertion.result ) { + good++; + } else { + bad++; + config.stats.bad++; + config.moduleStats.bad++; + } + } + + // store result when possible + if ( QUnit.config.reorder && defined.sessionStorage ) { + if ( bad ) { + sessionStorage.setItem( "qunit-test-" + this.module + "-" + this.testName, bad ); + } else { + sessionStorage.removeItem( "qunit-test-" + this.module + "-" + this.testName ); + } + } + + if ( bad === 0 ) { + addClass( ol, "qunit-collapsed" ); + } + + // `b` initialized at top of scope + b = document.createElement( "strong" ); + b.innerHTML = this.nameHtml + " <b class='counts'>(<b class='failed'>" + bad + "</b>, <b class='passed'>" + good + "</b>, " + this.assertions.length + ")</b>"; + + addEvent(b, "click", function() { + var next = b.parentNode.lastChild, + collapsed = hasClass( next, "qunit-collapsed" ); + ( collapsed ? removeClass : addClass )( next, "qunit-collapsed" ); + }); + + addEvent(b, "dblclick", function( e ) { + var target = e && e.target ? e.target : window.event.srcElement; + if ( target.nodeName.toLowerCase() === "span" || target.nodeName.toLowerCase() === "b" ) { + target = target.parentNode; + } + if ( window.location && target.nodeName.toLowerCase() === "strong" ) { + window.location = QUnit.url({ testNumber: test.testNumber }); + } + }); + + // `time` initialized at top of scope + time = document.createElement( "span" ); + time.className = "runtime"; + time.innerHTML = this.runtime + " ms"; + + // `li` initialized at top of scope + li = id( this.id ); + li.className = bad ? "fail" : "pass"; + li.removeChild( li.firstChild ); + a = li.firstChild; + li.appendChild( b ); + li.appendChild( a ); + li.appendChild( time ); + li.appendChild( ol ); + + } else { + for ( i = 0; i < this.assertions.length; i++ ) { + if ( !this.assertions[i].result ) { + bad++; + config.stats.bad++; + config.moduleStats.bad++; + } + } + } + + runLoggingCallbacks( "testDone", QUnit, { + name: this.testName, + module: this.module, + failed: bad, + passed: this.assertions.length - bad, + total: this.assertions.length, + runtime: this.runtime, + // DEPRECATED: this property will be removed in 2.0.0, use runtime instead + duration: this.runtime + }); + + QUnit.reset(); + + config.current = undefined; + }, + + queue: function() { + var bad, + test = this; + + synchronize(function() { + test.init(); + }); + function run() { + // each of these can by async + synchronize(function() { + test.setup(); + }); + synchronize(function() { + test.run(); + }); + synchronize(function() { + test.teardown(); + }); + synchronize(function() { + test.finish(); + }); + } + + // `bad` initialized at top of scope + // defer when previous test run passed, if storage is available + bad = QUnit.config.reorder && defined.sessionStorage && + +sessionStorage.getItem( "qunit-test-" + this.module + "-" + this.testName ); + + if ( bad ) { + run(); + } else { + synchronize( run, true ); + } + } +}; + +// `assert` initialized at top of scope +// Assert helpers +// All of these must either call QUnit.push() or manually do: +// - runLoggingCallbacks( "log", .. ); +// - config.current.assertions.push({ .. }); +assert = QUnit.assert = { + /** + * Asserts rough true-ish result. + * @name ok + * @function + * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); + */ + ok: function( result, msg ) { + if ( !config.current ) { + throw new Error( "ok() assertion outside test context, was " + sourceFromStacktrace(2) ); + } + result = !!result; + msg = msg || ( result ? "okay" : "failed" ); + + var source, + details = { + module: config.current.module, + name: config.current.testName, + result: result, + message: msg + }; + + msg = "<span class='test-message'>" + escapeText( msg ) + "</span>"; + + if ( !result ) { + source = sourceFromStacktrace( 2 ); + if ( source ) { + details.source = source; + msg += "<table><tr class='test-source'><th>Source: </th><td><pre>" + + escapeText( source ) + + "</pre></td></tr></table>"; + } + } + runLoggingCallbacks( "log", QUnit, details ); + config.current.assertions.push({ + result: result, + message: msg + }); + }, + + /** + * Assert that the first two arguments are equal, with an optional message. + * Prints out both actual and expected values. + * @name equal + * @function + * @example equal( format( "Received {0} bytes.", 2), "Received 2 bytes.", "format() replaces {0} with next argument" ); + */ + equal: function( actual, expected, message ) { + /*jshint eqeqeq:false */ + QUnit.push( expected == actual, actual, expected, message ); + }, + + /** + * @name notEqual + * @function + */ + notEqual: function( actual, expected, message ) { + /*jshint eqeqeq:false */ + QUnit.push( expected != actual, actual, expected, message ); + }, + + /** + * @name propEqual + * @function + */ + propEqual: function( actual, expected, message ) { + actual = objectValues(actual); + expected = objectValues(expected); + QUnit.push( QUnit.equiv(actual, expected), actual, expected, message ); + }, + + /** + * @name notPropEqual + * @function + */ + notPropEqual: function( actual, expected, message ) { + actual = objectValues(actual); + expected = objectValues(expected); + QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message ); + }, + + /** + * @name deepEqual + * @function + */ + deepEqual: function( actual, expected, message ) { + QUnit.push( QUnit.equiv(actual, expected), actual, expected, message ); + }, + + /** + * @name notDeepEqual + * @function + */ + notDeepEqual: function( actual, expected, message ) { + QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message ); + }, + + /** + * @name strictEqual + * @function + */ + strictEqual: function( actual, expected, message ) { + QUnit.push( expected === actual, actual, expected, message ); + }, + + /** + * @name notStrictEqual + * @function + */ + notStrictEqual: function( actual, expected, message ) { + QUnit.push( expected !== actual, actual, expected, message ); + }, + + "throws": function( block, expected, message ) { + var actual, + expectedOutput = expected, + ok = false; + + // 'expected' is optional + if ( !message && typeof expected === "string" ) { + message = expected; + expected = null; + } + + config.current.ignoreGlobalErrors = true; + try { + block.call( config.current.testEnvironment ); + } catch (e) { + actual = e; + } + config.current.ignoreGlobalErrors = false; + + if ( actual ) { + + // we don't want to validate thrown error + if ( !expected ) { + ok = true; + expectedOutput = null; + + // expected is an Error object + } else if ( expected instanceof Error ) { + ok = actual instanceof Error && + actual.name === expected.name && + actual.message === expected.message; + + // expected is a regexp + } else if ( QUnit.objectType( expected ) === "regexp" ) { + ok = expected.test( errorString( actual ) ); + + // expected is a string + } else if ( QUnit.objectType( expected ) === "string" ) { + ok = expected === errorString( actual ); + + // expected is a constructor + } else if ( actual instanceof expected ) { + ok = true; + + // expected is a validation function which returns true is validation passed + } else if ( expected.call( {}, actual ) === true ) { + expectedOutput = null; + ok = true; + } + + QUnit.push( ok, actual, expectedOutput, message ); + } else { + QUnit.pushFailure( message, null, "No exception was thrown." ); + } + } +}; + +/** + * @deprecated since 1.8.0 + * Kept assertion helpers in root for backwards compatibility. + */ +extend( QUnit.constructor.prototype, assert ); + +/** + * @deprecated since 1.9.0 + * Kept to avoid TypeErrors for undefined methods. + */ +QUnit.constructor.prototype.raises = function() { + QUnit.push( false, false, false, "QUnit.raises has been deprecated since 2012 (fad3c1ea), use QUnit.throws instead" ); +}; + +/** + * @deprecated since 1.0.0, replaced with error pushes since 1.3.0 + * Kept to avoid TypeErrors for undefined methods. + */ +QUnit.constructor.prototype.equals = function() { + QUnit.push( false, false, false, "QUnit.equals has been deprecated since 2009 (e88049a0), use QUnit.equal instead" ); +}; +QUnit.constructor.prototype.same = function() { + QUnit.push( false, false, false, "QUnit.same has been deprecated since 2009 (e88049a0), use QUnit.deepEqual instead" ); +}; + +// Test for equality any JavaScript type. +// Author: Philippe Rathé <prathe@gmail.com> +QUnit.equiv = (function() { + + // Call the o related callback with the given arguments. + function bindCallbacks( o, callbacks, args ) { + var prop = QUnit.objectType( o ); + if ( prop ) { + if ( QUnit.objectType( callbacks[ prop ] ) === "function" ) { + return callbacks[ prop ].apply( callbacks, args ); + } else { + return callbacks[ prop ]; // or undefined + } + } + } + + // the real equiv function + var innerEquiv, + // stack to decide between skip/abort functions + callers = [], + // stack to avoiding loops from circular referencing + parents = [], + parentsB = [], + + getProto = Object.getPrototypeOf || function ( obj ) { + /*jshint camelcase:false */ + return obj.__proto__; + }, + callbacks = (function () { + + // for string, boolean, number and null + function useStrictEquality( b, a ) { + /*jshint eqeqeq:false */ + if ( b instanceof a.constructor || a instanceof b.constructor ) { + // to catch short annotation VS 'new' annotation of a + // declaration + // e.g. var i = 1; + // var j = new Number(1); + return a == b; + } else { + return a === b; + } + } + + return { + "string": useStrictEquality, + "boolean": useStrictEquality, + "number": useStrictEquality, + "null": useStrictEquality, + "undefined": useStrictEquality, + + "nan": function( b ) { + return isNaN( b ); + }, + + "date": function( b, a ) { + return QUnit.objectType( b ) === "date" && a.valueOf() === b.valueOf(); + }, + + "regexp": function( b, a ) { + return QUnit.objectType( b ) === "regexp" && + // the regex itself + a.source === b.source && + // and its modifiers + a.global === b.global && + // (gmi) ... + a.ignoreCase === b.ignoreCase && + a.multiline === b.multiline && + a.sticky === b.sticky; + }, + + // - skip when the property is a method of an instance (OOP) + // - abort otherwise, + // initial === would have catch identical references anyway + "function": function() { + var caller = callers[callers.length - 1]; + return caller !== Object && typeof caller !== "undefined"; + }, + + "array": function( b, a ) { + var i, j, len, loop, aCircular, bCircular; + + // b could be an object literal here + if ( QUnit.objectType( b ) !== "array" ) { + return false; + } + + len = a.length; + if ( len !== b.length ) { + // safe and faster + return false; + } + + // track reference to avoid circular references + parents.push( a ); + parentsB.push( b ); + for ( i = 0; i < len; i++ ) { + loop = false; + for ( j = 0; j < parents.length; j++ ) { + aCircular = parents[j] === a[i]; + bCircular = parentsB[j] === b[i]; + if ( aCircular || bCircular ) { + if ( a[i] === b[i] || aCircular && bCircular ) { + loop = true; + } else { + parents.pop(); + parentsB.pop(); + return false; + } + } + } + if ( !loop && !innerEquiv(a[i], b[i]) ) { + parents.pop(); + parentsB.pop(); + return false; + } + } + parents.pop(); + parentsB.pop(); + return true; + }, + + "object": function( b, a ) { + /*jshint forin:false */ + var i, j, loop, aCircular, bCircular, + // Default to true + eq = true, + aProperties = [], + bProperties = []; + + // comparing constructors is more strict than using + // instanceof + if ( a.constructor !== b.constructor ) { + // Allow objects with no prototype to be equivalent to + // objects with Object as their constructor. + if ( !(( getProto(a) === null && getProto(b) === Object.prototype ) || + ( getProto(b) === null && getProto(a) === Object.prototype ) ) ) { + return false; + } + } + + // stack constructor before traversing properties + callers.push( a.constructor ); + + // track reference to avoid circular references + parents.push( a ); + parentsB.push( b ); + + // be strict: don't ensure hasOwnProperty and go deep + for ( i in a ) { + loop = false; + for ( j = 0; j < parents.length; j++ ) { + aCircular = parents[j] === a[i]; + bCircular = parentsB[j] === b[i]; + if ( aCircular || bCircular ) { + if ( a[i] === b[i] || aCircular && bCircular ) { + loop = true; + } else { + eq = false; + break; + } + } + } + aProperties.push(i); + if ( !loop && !innerEquiv(a[i], b[i]) ) { + eq = false; + break; + } + } + + parents.pop(); + parentsB.pop(); + callers.pop(); // unstack, we are done + + for ( i in b ) { + bProperties.push( i ); // collect b's properties + } + + // Ensures identical properties name + return eq && innerEquiv( aProperties.sort(), bProperties.sort() ); + } + }; + }()); + + innerEquiv = function() { // can take multiple arguments + var args = [].slice.apply( arguments ); + if ( args.length < 2 ) { + return true; // end transition + } + + return (function( a, b ) { + if ( a === b ) { + return true; // catch the most you can + } else if ( a === null || b === null || typeof a === "undefined" || + typeof b === "undefined" || + QUnit.objectType(a) !== QUnit.objectType(b) ) { + return false; // don't lose time with error prone cases + } else { + return bindCallbacks(a, callbacks, [ b, a ]); + } + + // apply transition with (1..n) arguments + }( args[0], args[1] ) && innerEquiv.apply( this, args.splice(1, args.length - 1 )) ); + }; + + return innerEquiv; +}()); + +/** + * jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | + * http://flesler.blogspot.com Licensed under BSD + * (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008 + * + * @projectDescription Advanced and extensible data dumping for Javascript. + * @version 1.0.0 + * @author Ariel Flesler + * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html} + */ +QUnit.jsDump = (function() { + function quote( str ) { + return "\"" + str.toString().replace( /"/g, "\\\"" ) + "\""; + } + function literal( o ) { + return o + ""; + } + function join( pre, arr, post ) { + var s = jsDump.separator(), + base = jsDump.indent(), + inner = jsDump.indent(1); + if ( arr.join ) { + arr = arr.join( "," + s + inner ); + } + if ( !arr ) { + return pre + post; + } + return [ pre, inner + arr, base + post ].join(s); + } + function array( arr, stack ) { + var i = arr.length, ret = new Array(i); + this.up(); + while ( i-- ) { + ret[i] = this.parse( arr[i] , undefined , stack); + } + this.down(); + return join( "[", ret, "]" ); + } + + var reName = /^function (\w+)/, + jsDump = { + // type is used mostly internally, you can fix a (custom)type in advance + parse: function( obj, type, stack ) { + stack = stack || [ ]; + var inStack, res, + parser = this.parsers[ type || this.typeOf(obj) ]; + + type = typeof parser; + inStack = inArray( obj, stack ); + + if ( inStack !== -1 ) { + return "recursion(" + (inStack - stack.length) + ")"; + } + if ( type === "function" ) { + stack.push( obj ); + res = parser.call( this, obj, stack ); + stack.pop(); + return res; + } + return ( type === "string" ) ? parser : this.parsers.error; + }, + typeOf: function( obj ) { + var type; + if ( obj === null ) { + type = "null"; + } else if ( typeof obj === "undefined" ) { + type = "undefined"; + } else if ( QUnit.is( "regexp", obj) ) { + type = "regexp"; + } else if ( QUnit.is( "date", obj) ) { + type = "date"; + } else if ( QUnit.is( "function", obj) ) { + type = "function"; + } else if ( typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined" ) { + type = "window"; + } else if ( obj.nodeType === 9 ) { + type = "document"; + } else if ( obj.nodeType ) { + type = "node"; + } else if ( + // native arrays + toString.call( obj ) === "[object Array]" || + // NodeList objects + ( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) ) + ) { + type = "array"; + } else if ( obj.constructor === Error.prototype.constructor ) { + type = "error"; + } else { + type = typeof obj; + } + return type; + }, + separator: function() { + return this.multiline ? this.HTML ? "<br />" : "\n" : this.HTML ? " " : " "; + }, + // extra can be a number, shortcut for increasing-calling-decreasing + indent: function( extra ) { + if ( !this.multiline ) { + return ""; + } + var chr = this.indentChar; + if ( this.HTML ) { + chr = chr.replace( /\t/g, " " ).replace( / /g, " " ); + } + return new Array( this.depth + ( extra || 0 ) ).join(chr); + }, + up: function( a ) { + this.depth += a || 1; + }, + down: function( a ) { + this.depth -= a || 1; + }, + setParser: function( name, parser ) { + this.parsers[name] = parser; + }, + // The next 3 are exposed so you can use them + quote: quote, + literal: literal, + join: join, + // + depth: 1, + // This is the list of parsers, to modify them, use jsDump.setParser + parsers: { + window: "[Window]", + document: "[Document]", + error: function(error) { + return "Error(\"" + error.message + "\")"; + }, + unknown: "[Unknown]", + "null": "null", + "undefined": "undefined", + "function": function( fn ) { + var ret = "function", + // functions never have name in IE + name = "name" in fn ? fn.name : (reName.exec(fn) || [])[1]; + + if ( name ) { + ret += " " + name; + } + ret += "( "; + + ret = [ ret, QUnit.jsDump.parse( fn, "functionArgs" ), "){" ].join( "" ); + return join( ret, QUnit.jsDump.parse(fn,"functionCode" ), "}" ); + }, + array: array, + nodelist: array, + "arguments": array, + object: function( map, stack ) { + /*jshint forin:false */ + var ret = [ ], keys, key, val, i; + QUnit.jsDump.up(); + keys = []; + for ( key in map ) { + keys.push( key ); + } + keys.sort(); + for ( i = 0; i < keys.length; i++ ) { + key = keys[ i ]; + val = map[ key ]; + ret.push( QUnit.jsDump.parse( key, "key" ) + ": " + QUnit.jsDump.parse( val, undefined, stack ) ); + } + QUnit.jsDump.down(); + return join( "{", ret, "}" ); + }, + node: function( node ) { + var len, i, val, + open = QUnit.jsDump.HTML ? "<" : "<", + close = QUnit.jsDump.HTML ? ">" : ">", + tag = node.nodeName.toLowerCase(), + ret = open + tag, + attrs = node.attributes; + + if ( attrs ) { + for ( i = 0, len = attrs.length; i < len; i++ ) { + val = attrs[i].nodeValue; + // IE6 includes all attributes in .attributes, even ones not explicitly set. + // Those have values like undefined, null, 0, false, "" or "inherit". + if ( val && val !== "inherit" ) { + ret += " " + attrs[i].nodeName + "=" + QUnit.jsDump.parse( val, "attribute" ); + } + } + } + ret += close; + + // Show content of TextNode or CDATASection + if ( node.nodeType === 3 || node.nodeType === 4 ) { + ret += node.nodeValue; + } + + return ret + open + "/" + tag + close; + }, + // function calls it internally, it's the arguments part of the function + functionArgs: function( fn ) { + var args, + l = fn.length; + + if ( !l ) { + return ""; + } + + args = new Array(l); + while ( l-- ) { + // 97 is 'a' + args[l] = String.fromCharCode(97+l); + } + return " " + args.join( ", " ) + " "; + }, + // object calls it internally, the key part of an item in a map + key: quote, + // function calls it internally, it's the content of the function + functionCode: "[code]", + // node calls it internally, it's an html attribute value + attribute: quote, + string: quote, + date: quote, + regexp: literal, + number: literal, + "boolean": literal + }, + // if true, entities are escaped ( <, >, \t, space and \n ) + HTML: false, + // indentation unit + indentChar: " ", + // if true, items in a collection, are separated by a \n, else just a space. + multiline: true + }; + + return jsDump; +}()); + +/* + * Javascript Diff Algorithm + * By John Resig (http://ejohn.org/) + * Modified by Chu Alan "sprite" + * + * Released under the MIT license. + * + * More Info: + * http://ejohn.org/projects/javascript-diff-algorithm/ + * + * Usage: QUnit.diff(expected, actual) + * + * QUnit.diff( "the quick brown fox jumped over", "the quick fox jumps over" ) == "the quick <del>brown </del> fox <del>jumped </del><ins>jumps </ins> over" + */ +QUnit.diff = (function() { + /*jshint eqeqeq:false, eqnull:true */ + function diff( o, n ) { + var i, + ns = {}, + os = {}; + + for ( i = 0; i < n.length; i++ ) { + if ( !hasOwn.call( ns, n[i] ) ) { + ns[ n[i] ] = { + rows: [], + o: null + }; + } + ns[ n[i] ].rows.push( i ); + } + + for ( i = 0; i < o.length; i++ ) { + if ( !hasOwn.call( os, o[i] ) ) { + os[ o[i] ] = { + rows: [], + n: null + }; + } + os[ o[i] ].rows.push( i ); + } + + for ( i in ns ) { + if ( hasOwn.call( ns, i ) ) { + if ( ns[i].rows.length === 1 && hasOwn.call( os, i ) && os[i].rows.length === 1 ) { + n[ ns[i].rows[0] ] = { + text: n[ ns[i].rows[0] ], + row: os[i].rows[0] + }; + o[ os[i].rows[0] ] = { + text: o[ os[i].rows[0] ], + row: ns[i].rows[0] + }; + } + } + } + + for ( i = 0; i < n.length - 1; i++ ) { + if ( n[i].text != null && n[ i + 1 ].text == null && n[i].row + 1 < o.length && o[ n[i].row + 1 ].text == null && + n[ i + 1 ] == o[ n[i].row + 1 ] ) { + + n[ i + 1 ] = { + text: n[ i + 1 ], + row: n[i].row + 1 + }; + o[ n[i].row + 1 ] = { + text: o[ n[i].row + 1 ], + row: i + 1 + }; + } + } + + for ( i = n.length - 1; i > 0; i-- ) { + if ( n[i].text != null && n[ i - 1 ].text == null && n[i].row > 0 && o[ n[i].row - 1 ].text == null && + n[ i - 1 ] == o[ n[i].row - 1 ]) { + + n[ i - 1 ] = { + text: n[ i - 1 ], + row: n[i].row - 1 + }; + o[ n[i].row - 1 ] = { + text: o[ n[i].row - 1 ], + row: i - 1 + }; + } + } + + return { + o: o, + n: n + }; + } + + return function( o, n ) { + o = o.replace( /\s+$/, "" ); + n = n.replace( /\s+$/, "" ); + + var i, pre, + str = "", + out = diff( o === "" ? [] : o.split(/\s+/), n === "" ? [] : n.split(/\s+/) ), + oSpace = o.match(/\s+/g), + nSpace = n.match(/\s+/g); + + if ( oSpace == null ) { + oSpace = [ " " ]; + } + else { + oSpace.push( " " ); + } + + if ( nSpace == null ) { + nSpace = [ " " ]; + } + else { + nSpace.push( " " ); + } + + if ( out.n.length === 0 ) { + for ( i = 0; i < out.o.length; i++ ) { + str += "<del>" + out.o[i] + oSpace[i] + "</del>"; + } + } + else { + if ( out.n[0].text == null ) { + for ( n = 0; n < out.o.length && out.o[n].text == null; n++ ) { + str += "<del>" + out.o[n] + oSpace[n] + "</del>"; + } + } + + for ( i = 0; i < out.n.length; i++ ) { + if (out.n[i].text == null) { + str += "<ins>" + out.n[i] + nSpace[i] + "</ins>"; + } + else { + // `pre` initialized at top of scope + pre = ""; + + for ( n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++ ) { + pre += "<del>" + out.o[n] + oSpace[n] + "</del>"; + } + str += " " + out.n[i].text + nSpace[i] + pre; + } + } + } + + return str; + }; +}()); + +// For browser, export only select globals +if ( typeof window !== "undefined" ) { + extend( window, QUnit.constructor.prototype ); + window.QUnit = QUnit; +} + +// For CommonJS environments, export everything +if ( typeof module !== "undefined" && module.exports ) { + module.exports = QUnit; +} + + +// Get a reference to the global object, like window in browsers +}( (function() { + return this; +})() )); diff --git a/actionview/test/ujs/server.rb b/actionview/test/ujs/server.rb new file mode 100644 index 0000000000..7d1bab4b2a --- /dev/null +++ b/actionview/test/ujs/server.rb @@ -0,0 +1,74 @@ +# frozen_string_literal: true + +require "rack" +require "rails" +require "action_controller/railtie" +require "action_view/railtie" +require "blade" +require "json" + +module UJS + class Server < Rails::Application + routes.append do + get "/rails-ujs.js" => Blade::Assets.environment + get "/" => "tests#index" + match "/echo" => "tests#echo", via: :all + get "/error" => proc { |env| [403, {}, []] } + end + + config.cache_classes = false + config.eager_load = false + config.secret_key_base = "59d7a4dbd349fa3838d79e330e39690fc22b931e7dc17d9162f03d633d526fbb92dfdb2dc9804c8be3e199631b9c1fbe43fc3e4fc75730b515851849c728d5c7" + config.paths["app/views"].unshift("#{Rails.root}/views") + config.public_file_server.enabled = true + config.logger = Logger.new(STDOUT) + config.log_level = :error + end +end + +module TestsHelper + def test_to(*names) + names = ["/vendor/qunit.js", "settings"] + names + names.map { |name| script_tag name }.join("\n").html_safe + end + + def script_tag(src) + src = "/test/#{src}.js" unless src.index("/") + %(<script src="#{src}" type="text/javascript"></script>).html_safe + end +end + +class TestsController < ActionController::Base + helper TestsHelper + layout "application" + + def index + render :index + end + + def echo + data = { params: params.to_unsafe_h }.update(request.env) + + if params[:content_type] && params[:content] + render inline: params[:content], content_type: params[:content_type] + elsif request.xhr? + render json: JSON.generate(data) + elsif params[:iframe] + payload = JSON.generate(data).gsub("<", "<").gsub(">", ">") + html = <<-HTML + <script> + if (window.top && window.top !== window) + window.top.jQuery.event.trigger('iframe:loaded', #{payload}) + </script> + <p>You shouldn't be seeing this. <a href="#{request.env['HTTP_REFERER']}">Go back</a></p> + HTML + + render html: html.html_safe + else + render plain: "ERROR: #{request.path} requested without ajax", status: 404 + end + end +end + +Blade.initialize! +UJS::Server.initialize! diff --git a/actionview/test/ujs/views/layouts/application.html.erb b/actionview/test/ujs/views/layouts/application.html.erb new file mode 100644 index 0000000000..c787e77b84 --- /dev/null +++ b/actionview/test/ujs/views/layouts/application.html.erb @@ -0,0 +1,25 @@ +<!DOCTYPE html> +<html id="html"> + <head> + <title><%= @title %></title> + <link href="/vendor/qunit.css" media="screen" rel="stylesheet" type="text/css" media="screen, projection" /> + <script src="/vendor/jquery-2.2.0.js" type="text/javascript"></script> + <script> + // This is for test in override.js. + // Must go before rails-ujs. + document.addEventListener('rails:attachBindings', function() { + window.Rails.linkClickSelector += ', a[data-custom-remote-link]'; + // Hijacks link click before ujs binds any handlers + // This is only used for ctrl-clicking test on remote links + window.Rails.delegate(document, '#qunit-fixture a', 'click', function(e) { + e.preventDefault(); + }); + }); + </script> + <%= script_tag "/rails-ujs.js" %> + </head> + + <body id="body"> + <%= yield %> + </body> +</html> diff --git a/actionview/test/ujs/views/tests/index.html.erb b/actionview/test/ujs/views/tests/index.html.erb new file mode 100644 index 0000000000..6b16535216 --- /dev/null +++ b/actionview/test/ujs/views/tests/index.html.erb @@ -0,0 +1,11 @@ +<% @title = "rails-ujs test" %> + +<%= test_to 'data-confirm', 'data-remote', 'data-disable', 'data-disable-with', 'call-remote', 'call-remote-callbacks', 'data-method', 'override', 'csrf-refresh', 'csrf-token', 'call-ajax' %> + +<h1 id="qunit-header"><%= @title %></h1> +<h2 id="qunit-banner"></h2> +<div id="qunit-testrunner-toolbar"></div> +<h2 id="qunit-userAgent"></h2> +<ol id="qunit-tests"></ol> + +<div id="qunit-fixture"></div> |