diff options
Diffstat (limited to 'actionview/test')
44 files changed, 7697 insertions, 175 deletions
diff --git a/actionview/test/abstract_unit.rb b/actionview/test/abstract_unit.rb index 88c7189d22..5bc4151087 100644 --- a/actionview/test/abstract_unit.rb +++ b/actionview/test/abstract_unit.rb @@ -163,7 +163,7 @@ class ActionDispatch::IntegrationTest < ActiveSupport::TestCase # 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 + private def controller_reference(controller_param) controller_param end diff --git a/actionview/test/actionpack/abstract/helper_test.rb b/actionview/test/actionpack/abstract/helper_test.rb index 5a2f0839e5..83237518d7 100644 --- a/actionview/test/actionpack/abstract/helper_test.rb +++ b/actionview/test/actionpack/abstract/helper_test.rb @@ -109,7 +109,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/controller/layout_test.rb b/actionview/test/actionpack/controller/layout_test.rb index 00147d31f3..b79835ff34 100644 --- a/actionview/test/actionpack/controller/layout_test.rb +++ b/actionview/test/actionpack/controller/layout_test.rb @@ -1,6 +1,5 @@ require "abstract_unit" require "active_support/core_ext/array/extract_options" -require "active_support/core_ext/regexp" # 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. @@ -253,7 +252,7 @@ class LayoutStatusIsRenderedTest < ActionController::TestCase end end -unless /mswin|mingw/.match?(RbConfig::CONFIG["host_os"]) +unless Gem.win_platform? class LayoutSymlinkedTest < LayoutTest layout "symlinked/symlinked_layout" end diff --git a/actionview/test/actionpack/controller/render_test.rb b/actionview/test/actionpack/controller/render_test.rb index cd89dceb45..b4a757d6b8 100644 --- a/actionview/test/actionpack/controller/render_test.rb +++ b/actionview/test/actionpack/controller/render_test.rb @@ -11,7 +11,7 @@ class Customer < Struct.new(:name, :id) undef_method :to_json - def to_xml(options={}) + def to_xml(options = {}) if options[:builder] options[:builder].name name else @@ -19,7 +19,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 diff --git a/actionview/test/activerecord/form_helper_activerecord_test.rb b/actionview/test/activerecord/form_helper_activerecord_test.rb index 6152ec4720..0f7960b408 100644 --- a/actionview/test/activerecord/form_helper_activerecord_test.rb +++ b/actionview/test/activerecord/form_helper_activerecord_test.rb @@ -52,7 +52,7 @@ class FormHelperActiveRecordTest < ActionView::TestCase assert_dom_equal expected, output_buffer end - protected + private def hidden_fields(method = nil) txt = %{<input name="utf8" type="hidden" value="✓" />} diff --git a/actionview/test/activerecord/relation_cache_test.rb b/actionview/test/activerecord/relation_cache_test.rb index 880e80a8dc..43f7242ee9 100644 --- a/actionview/test/activerecord/relation_cache_test.rb +++ b/actionview/test/activerecord/relation_cache_test.rb @@ -1,6 +1,6 @@ require "active_record_unit" -class RelationCacheTest < ActionView::TestCase +class RelationCacheTest < ActionView::TestCase tests ActionView::Helpers::CacheHelper def setup 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/lib/controller/fake_models.rb b/actionview/test/lib/controller/fake_models.rb index cc5f5c1d59..80649db88b 100644 --- a/actionview/test/lib/controller/fake_models.rb +++ b/actionview/test/lib/controller/fake_models.rb @@ -6,7 +6,7 @@ class Customer < Struct.new(:name, :id) undef_method :to_json - def to_xml(options={}) + def to_xml(options = {}) if options[:builder] options[:builder].name name else @@ -14,7 +14,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 diff --git a/actionview/test/template/asset_tag_helper_test.rb b/actionview/test/template/asset_tag_helper_test.rb index 3bdab42f7a..07a6452cc1 100644 --- a/actionview/test/template/asset_tag_helper_test.rb +++ b/actionview/test/template/asset_tag_helper_test.rb @@ -630,7 +630,7 @@ 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 diff --git a/actionview/test/template/capture_helper_test.rb b/actionview/test/template/capture_helper_test.rb index 54bf9b4c33..7f37523eeb 100644 --- a/actionview/test/template/capture_helper_test.rb +++ b/actionview/test/template/capture_helper_test.rb @@ -127,18 +127,18 @@ class CaptureHelperTest < ActionView::TestCase 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_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_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_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 diff --git a/actionview/test/template/compiled_templates_test.rb b/actionview/test/template/compiled_templates_test.rb index 3ecac46d34..40ac867b38 100644 --- a/actionview/test/template/compiled_templates_test.rb +++ b/actionview/test/template/compiled_templates_test.rb @@ -24,6 +24,16 @@ class CompiledTemplatesTest < ActiveSupport::TestCase 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 diff --git a/actionview/test/template/date_helper_test.rb b/actionview/test/template/date_helper_test.rb index 44e5a8c346..a84ac18bee 100644 --- a/actionview/test/template/date_helper_test.rb +++ b/actionview/test/template/date_helper_test.rb @@ -18,7 +18,7 @@ class DateHelperTest < ActionView::TestCase 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 @@ -167,9 +167,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 @@ -385,7 +385,7 @@ class DateHelperTest < ActionView::TestCase 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) } + 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) @@ -848,7 +848,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">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" @@ -881,8 +881,8 @@ class DateHelperTest < ActionView::TestCase 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) + (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 @@ -900,12 +900,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) 2003.upto(2008) do |y| if y == 2003 expected << %(<option value="#{y}" selected="selected">#{y}</option>\n) @@ -929,8 +929,8 @@ class DateHelperTest < ActionView::TestCase 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) + (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 @@ -969,8 +969,8 @@ class DateHelperTest < ActionView::TestCase 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) + (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) @@ -981,7 +981,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">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 @@ -1002,8 +1002,8 @@ class DateHelperTest < ActionView::TestCase 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) + (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) @@ -1018,8 +1018,8 @@ class DateHelperTest < ActionView::TestCase 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) + (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) @@ -1286,8 +1286,8 @@ class DateHelperTest < ActionView::TestCase 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) + (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) @@ -1709,7 +1709,7 @@ class DateHelperTest < ActionView::TestCase 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) 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) @@ -1733,7 +1733,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) 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) @@ -1851,7 +1851,7 @@ class DateHelperTest < ActionView::TestCase expected = "<input type=\"hidden\" id=\"post_written_on_3i\" name=\"post[written_on(3i)]\" value=\"1\" />\n" - expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n} + expected << %{<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" @@ -1882,7 +1882,7 @@ class DateHelperTest < ActionView::TestCase expected = "<input type=\"hidden\" id=\"post_written_on_3i\" name=\"post[written_on(3i)]\" value=\"1\" />\n" - expected << %{<select id="post_written_on_2i" name="post[written_on(2i)]">\n} + expected << %{<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" @@ -1901,7 +1901,7 @@ class DateHelperTest < ActionView::TestCase expected = "<input type=\"hidden\" id=\"post_written_on_3i\" disabled=\"disabled\" name=\"post[written_on(3i)]\" value=\"1\" />\n" - 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" @@ -2003,7 +2003,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} 1.upto(31) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == 15}>#{i}</option>\n) } expected << "</select>\n" @@ -2011,7 +2011,7 @@ 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" @@ -2021,8 +2021,8 @@ class DateHelperTest < ActionView::TestCase def test_date_select_with_nil @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} start_year.upto(end_year) { |i| expected << %(<option value="#{i}"#{' selected="selected"' if i == Time.now.year}>#{i}</option>\n) } expected << "</select>\n" @@ -2041,8 +2041,8 @@ 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 + 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 << "<option value=\"\"></option>\n" start_year.upto(end_year) { |i| expected << %(<option value="#{i}">#{i}</option>\n) } @@ -2064,11 +2064,11 @@ class DateHelperTest < ActionView::TestCase 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" @@ -2084,8 +2084,8 @@ class DateHelperTest < ActionView::TestCase 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 << "<option value=\"\"></option>\n" @@ -2782,7 +2782,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 @@ -2903,8 +2903,8 @@ class DateHelperTest < ActionView::TestCase 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) + (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) @@ -2915,7 +2915,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">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 @@ -2936,8 +2936,8 @@ class DateHelperTest < ActionView::TestCase 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) + (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) @@ -2952,8 +2952,8 @@ class DateHelperTest < ActionView::TestCase 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) + (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) @@ -2968,8 +2968,8 @@ class DateHelperTest < ActionView::TestCase 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) + (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) diff --git a/actionview/test/template/digestor_test.rb b/actionview/test/template/digestor_test.rb index 093ff28c14..a814cab686 100644 --- a/actionview/test/template/digestor_test.rb +++ b/actionview/test/template/digestor_test.rb @@ -139,7 +139,7 @@ class TemplateDigestorTest < ActionView::TestCase end def test_getting_of_doubly_nested_dependencies - doubly_nested = [{ "comments/comments"=>["comments/comment"] }, "messages/message"] + doubly_nested = [{ "comments/comments" => ["comments/comment"] }, "messages/message"] assert_equal doubly_nested, nested_dependencies("messages/peek") end @@ -150,13 +150,13 @@ 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"] }] + nested_deps = [{ "comments/comments" => ["comments/comment"] }] assert_equal nested_deps, nested_dependencies("messages/thread") 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..3a91c7dce7 --- /dev/null +++ b/actionview/test/template/form_helper/form_with_test.rb @@ -0,0 +1,2231 @@ +require "abstract_unit" +require "controller/fake_models" + +class FormWithTest < ActionView::TestCase + include RenderERBUtils +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) + + "".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}"} + 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.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' />" + + "<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' />" + + "<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_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">' + 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">' + 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">' + 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]">' + 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]">', f.hidden_field(:private_property) + assert_dom_equal '<input type="hidden" name="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' />" + + "<label for='post_active_true'>true</label>" + + "<input checked='checked' name='post[active]' type='radio' value='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' />" + + "true</label>" + + "<label for='post_active_false'>" + + "<input checked='checked' name='post[active]' type='radio' value='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' />" + + "true</label>" + + "<label for='post_active_false'>" + + "<input checked='checked' name='post[active]' type='radio' value='false' />" + + "false</label>" + + "<input name='post[id]' type='hidden' value='1' />" + 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' />" + + "<label for='post_1_active_true'>true</label>" + + "<input checked='checked' name='post[1][active]' type='radio' value='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' />" + + "<label for='post_tag_ids_1'>Tag 1</label>" + + "<input name='post[tag_ids][]' type='checkbox' value='2' />" + + "<label for='post_tag_ids_2'>Tag 2</label>" + + "<input checked='checked' name='post[tag_ids][]' type='checkbox' value='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' />" + + "Tag 1</label>" + + "<label for='post_tag_ids_2'>" + + "<input name='post[tag_ids][]' type='checkbox' value='2' />" + + "Tag 2</label>" + + "<label for='post_tag_ids_3'>" + + "<input checked='checked' name='post[tag_ids][]' type='checkbox' value='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' />" + + "Tag 1</label>" + + "<label for='post_tag_ids_2'>" + + "<input name='post[tag_ids][]' type='checkbox' value='2' />" + + "Tag 2</label>" + + "<label for='post_tag_ids_3'>" + + "<input checked='checked' name='post[tag_ids][]' type='checkbox' value='3' />" + + "Tag 3</label>" + + "<input name='post[id]' type='hidden' value='1' />" + 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' />" + + "<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' />" + 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' />" + 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.' />" + + "<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' />" + + "<textarea name='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' />" + + "<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' />" + + "<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' />" + 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' />" + + "<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' />" + 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' />" + 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' />" + + "<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' />" + end + + assert_dom_equal expected, output_buffer + 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' />" + 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' />" + 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' />" + + "<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' />" + 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' />" + + "<textarea name='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' />" + 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' />" + + "<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' />" + 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='' /></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='' /></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_form_with_with_namespace + skip "Do namespaces still make sense?" + 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' 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' />" + 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]">' + 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">' + 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' />" + 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' />" + 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' />" + + "<input name='post[123][comment][][name]' type='text' value='new comment' />" + 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' />" + + "<input name='post[1][comment][1][name]' type='text' value='new comment' />" + 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' />" + 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' />" + 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' />" + 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' />" + 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' />" + 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' />" + end + whole_form("/posts/123", method: "patch") do + "<input name='post[1][comment][123][title]' type='text' value='Hello World' />" + 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" />' + + '<input name="post[author_attributes][name]" type="text" value="new author" />' + 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" />' + + '<input name="post[author_attributes][name]" type="text" value="author #321" />' + + '<input name="post[author_attributes][id]" type="hidden" value="321" />' + 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" />' + + '<input name="post[author_attributes][name]" type="text" value="author #321" />' + + '<input name="post[author_attributes][id]" type="hidden" value="321" />' + 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" />' + + '<input name="post[author_attributes][name]" type="text" value="author #321" />' + 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" />' + + '<input name="post[author_attributes][name]" type="text" value="author #321" />' + 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" />' + + '<input name="post[author_attributes][name]" type="text" value="author #321" />' + + '<input name="post[author_attributes][id]" type="hidden" value="321" />' + 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" />' + + '<input name="post[author_attributes][id]" type="hidden" value="321" />' + + '<input name="post[author_attributes][name]" type="text" value="author #321" />' + 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" />' + + '<input name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + + '<input name="post[comments_attributes][0][id]" type="hidden" value="1" />' + + '<input name="post[comments_attributes][1][name]" type="text" value="comment #2" />' + + '<input name="post[comments_attributes][1][id]" type="hidden" value="2" />' + 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" />' + + '<input name="post[author_attributes][name]" type="text" value="author #321" />' + + '<input name="post[author_attributes][id]" type="hidden" value="321" />' + + '<input name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + + '<input name="post[comments_attributes][1][name]" type="text" value="comment #2" />' + 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" />' + + '<input name="post[author_attributes][name]" type="text" value="author #321" />' + + '<input name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + + '<input name="post[comments_attributes][1][name]" type="text" value="comment #2" />' + 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" />' + + '<input name="post[author_attributes][name]" type="text" value="author #321" />' + + '<input name="post[author_attributes][id]" type="hidden" value="321" />' + + '<input name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + + '<input name="post[comments_attributes][1][name]" type="text" value="comment #2" />' + 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" />' + + '<input name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + + '<input name="post[comments_attributes][0][id]" type="hidden" value="1" />' + + '<input name="post[comments_attributes][1][name]" type="text" value="comment #2" />' + + '<input name="post[comments_attributes][1][id]" type="hidden" value="2" />' + 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" />' + + '<input name="post[comments_attributes][0][id]" type="hidden" value="1" />' + + '<input name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + + '<input name="post[comments_attributes][1][id]" type="hidden" value="2" />' + + '<input name="post[comments_attributes][1][name]" type="text" value="comment #2" />' + 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" />' + + '<input name="post[comments_attributes][0][name]" type="text" value="new comment" />' + + '<input name="post[comments_attributes][1][name]" type="text" value="new comment" />' + 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" />' + + '<input name="post[comments_attributes][0][name]" type="text" value="comment #321" />' + + '<input name="post[comments_attributes][0][id]" type="hidden" value="321" />' + + '<input name="post[comments_attributes][1][name]" type="text" value="new comment" />' + 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" />' + 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" />' + + '<input name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + + '<input name="post[comments_attributes][0][id]" type="hidden" value="1" />' + + '<input name="post[comments_attributes][1][name]" type="text" value="comment #2" />' + + '<input name="post[comments_attributes][1][id]" type="hidden" value="2" />' + 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" />' + + '<input name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + + '<input name="post[comments_attributes][0][id]" type="hidden" value="1" />' + + '<input name="post[comments_attributes][1][name]" type="text" value="comment #2" />' + + '<input name="post[comments_attributes][1][id]" type="hidden" value="2" />' + 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" />' + + '<input name="post[comments_attributes][0][name]" type="text" value="comment #1" />' + + '<input name="post[comments_attributes][0][id]" type="hidden" value="1" />' + + '<input name="post[comments_attributes][1][name]" type="text" value="comment #2" />' + + '<input name="post[comments_attributes][1][id]" type="hidden" value="2" />' + 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" />' + + '<input name="post[comments_attributes][0][name]" type="text" value="comment #321" />' + + '<input name="post[comments_attributes][0][id]" type="hidden" value="321" />' + + '<input name="post[comments_attributes][1][name]" type="text" value="new comment" />' + 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" />' + + '<input name="post[comments_attributes][abc][id]" type="hidden" value="321" />' + 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" />' + + '<input name="post[comments_attributes][abc][id]" type="hidden" value="321" />' + end + + assert_dom_equal expected, output_buffer + end + + class FakeAssociationProxy + def to_ary + [1, 2, 3] + 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" />' + + '<input name="post[comments_attributes][abc][id]" type="hidden" value="321" />' + 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 cf.index, expected + 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 cf.index, expected + 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 cf.index, expected + 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 cf.index, "abc" + } + 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" />' + + '<input name="post[comments_attributes][0][relevances_attributes][0][value]" type="text" value="commentrelevance #314" />' + + '<input name="post[comments_attributes][0][relevances_attributes][0][id]" type="hidden" value="314" />' + + '<input name="post[comments_attributes][0][id]" type="hidden" value="321" />' + + '<input name="post[tags_attributes][0][value]" type="text" value="tag #123" />' + + '<input name="post[tags_attributes][0][relevances_attributes][0][value]" type="text" value="tagrelevance #3141" />' + + '<input name="post[tags_attributes][0][relevances_attributes][0][id]" type="hidden" value="3141" />' + + '<input name="post[tags_attributes][0][id]" type="hidden" value="123" />' + + '<input name="post[tags_attributes][1][value]" type="text" value="tag #456" />' + + '<input name="post[tags_attributes][1][relevances_attributes][0][value]" type="text" value="tagrelevance #31415" />' + + '<input name="post[tags_attributes][1][relevances_attributes][0][id]" type="hidden" value="31415" />' + + '<input name="post[tags_attributes][1][id]" type="hidden" value="456" />' + 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" />' + 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' />" + + "<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' />" + + 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' />" + + "<textarea name='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' />" + + 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' />" + + "<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' />" + + 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' />" + + "<textarea name='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' />" + + 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' />" + + "<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' />" + + 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' />" + + "<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' />" + + 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' />", + 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' />", + 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' />" + + "<textarea name='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' />" + 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' />" + + "<textarea name='post[body]'>\nBack to the hill and over it again!</textarea>" + + "<input name='post[comment][name]' type='text' value='new comment' />" + 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' />" + 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' /><br/>" + + "<label for='body'>Body:</label> <textarea name='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' /><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' /><br/>" + + "<label for='body'>Body:</label> <textarea name='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' /><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' /><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' /><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' /><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' /><br/>" + + "<label for='body'>Body:</label> <textarea name='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' /><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 = "" + else + 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 + + 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}"} + 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 395c4e4f41..2bc0434771 100644 --- a/actionview/test/template/form_helper_test.rb +++ b/actionview/test/template/form_helper_test.rb @@ -257,7 +257,7 @@ 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_url", html: { id: "create-person" }) do |f| f.label(:name) end @@ -600,7 +600,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 @@ -746,7 +746,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) @@ -758,7 +758,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) @@ -1033,7 +1033,7 @@ 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 @@ -1141,7 +1141,7 @@ class FormHelperTest < ActionView::TestCase def test_datetime_field_with_value_attr 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) + value = DateTime.new(2013, 6, 29, 13, 37) assert_dom_equal(expected, datetime_field("post", "written_on", value: value)) end @@ -1436,7 +1436,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>}, @@ -1559,10 +1559,10 @@ class FormHelperTest < ActionView::TestCase expected = whole_form("/posts", "new_post", "new_post") do "<input type='hidden' name='post[active]' value='' />" + - "<label for='post_active_true'>"+ + "<label for='post_active_true'>" + "<input id='post_active_true' name='post[active]' type='radio' value='true' />" + "true</label>" + - "<label for='post_active_false'>"+ + "<label for='post_active_false'>" + "<input checked='checked' id='post_active_false' name='post[active]' type='radio' value='false' />" + "false</label>" end @@ -1585,12 +1585,12 @@ class FormHelperTest < ActionView::TestCase expected = whole_form("/posts", "new_post_1", "new_post") do "<input type='hidden' name='post[active]' value='' />" + - "<label for='post_active_true'>"+ + "<label for='post_active_true'>" + "<input id='post_active_true' name='post[active]' type='radio' value='true' />" + "true</label>" + - "<label for='post_active_false'>"+ + "<label for='post_active_false'>" + "<input checked='checked' id='post_active_false' name='post[active]' type='radio' value='false' />" + - "false</label>"+ + "false</label>" + "<input id='post_id' name='post[id]' type='hidden' value='1' />" end @@ -1698,7 +1698,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form("/posts", "new_post_1", "new_post") do - "<input name='post[tag_ids][]' type='hidden' value='' />"+ + "<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>" + @@ -1751,8 +1751,6 @@ 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| concat f.file_field(:file) end @@ -1765,8 +1763,6 @@ class FormHelperTest < ActionView::TestCase 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) @@ -1817,7 +1813,7 @@ class FormHelperTest < ActionView::TestCase concat f.submit("Create post") end - expected = whole_form("/posts/123", "create-post", "edit_other_name", method: "patch") do + 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>" + @@ -1833,9 +1829,9 @@ 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| @@ -1850,7 +1846,7 @@ class FormHelperTest < ActionView::TestCase concat f.check_box(:secret) end - expected = whole_form("/", "create-post", "edit_post", method: "delete") do + 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' />" + @@ -1867,7 +1863,7 @@ class FormHelperTest < ActionView::TestCase concat f.check_box(:secret) end - expected = whole_form("/", "create-post", "edit_post", method: "delete") do + 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' />" + @@ -1884,7 +1880,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 @@ -1898,7 +1894,7 @@ class FormHelperTest < ActionView::TestCase concat f.check_box(:secret) end - expected = whole_form("/", "create-post", "edit_post", method: "patch", remote: true) do + 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' />" + @@ -1939,7 +1935,7 @@ class FormHelperTest < ActionView::TestCase concat f.check_box(:secret) end - expected = whole_form("/", "create-post", "edit_post", method: "patch", remote: true) do + 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' />" + @@ -1958,7 +1954,7 @@ class FormHelperTest < ActionView::TestCase concat f.check_box(:secret) end - expected = whole_form("/posts", "new_post", "new_post", remote: true) do + 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' />" + @@ -2266,11 +2262,13 @@ class FormHelperTest < ActionView::TestCase 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' />" + "<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 @@ -2853,7 +2851,7 @@ 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 @@ -3443,7 +3441,7 @@ class FormHelperTest < ActionView::TestCase assert_equal 1, initialization_count, "form builder instantiated more than once" end - protected + private def hidden_fields(options = {}) method = options[:method] diff --git a/actionview/test/template/form_options_helper_test.rb b/actionview/test/template/form_options_helper_test.rb index 477d4f9eca..51f5d25958 100644 --- a/actionview/test/template/form_options_helper_test.rb +++ b/actionview/test/template/form_options_helper_test.rb @@ -258,7 +258,7 @@ 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") @@ -266,7 +266,7 @@ class FormOptionsHelperTest < ActionView::TestCase 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>), @@ -275,7 +275,7 @@ class FormOptionsHelperTest < ActionView::TestCase 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>), @@ -284,7 +284,7 @@ class FormOptionsHelperTest < ActionView::TestCase 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>), @@ -293,7 +293,7 @@ class FormOptionsHelperTest < ActionView::TestCase 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>), @@ -302,7 +302,7 @@ class FormOptionsHelperTest < ActionView::TestCase 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>), @@ -311,11 +311,11 @@ class FormOptionsHelperTest < ActionView::TestCase 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"]) + options_from_collection_for_select(albums, "id", "genre", ["1.0", "3.0"]) ) end @@ -335,9 +335,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 @@ -346,8 +346,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 @@ -356,38 +356,38 @@ 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...") + 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) + 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"]) + grouped_options_for_select("North America" => ["United States", "Canada"], "Europe" => ["Denmark", "Germany"]) ) end @@ -402,7 +402,7 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_time_zone_options_with_selected - opts = time_zone_options_for_select( "D" ) + 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" + @@ -412,7 +412,7 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_time_zone_options_with_unknown_selected - opts = time_zone_options_for_select( "K" ) + 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" + @@ -422,8 +422,8 @@ class FormOptionsHelperTest < ActionView::TestCase 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 ) + 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" + @@ -434,8 +434,8 @@ class FormOptionsHelperTest < ActionView::TestCase 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 ) + 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" + @@ -446,8 +446,8 @@ class FormOptionsHelperTest < ActionView::TestCase 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 ) + 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" + @@ -459,7 +459,7 @@ class FormOptionsHelperTest < ActionView::TestCase 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 @@ -628,7 +628,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 @@ -636,7 +636,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 @@ -644,7 +644,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 @@ -652,7 +652,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 @@ -1030,7 +1030,7 @@ class FormOptionsHelperTest < ActionView::TestCase def test_time_zone_select @firm = Firm.new("D") - html = time_zone_select( "firm", "time_zone" ) + 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" + @@ -1180,7 +1180,7 @@ class FormOptionsHelperTest < ActionView::TestCase 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 ) + 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>" + @@ -1236,7 +1236,7 @@ class FormOptionsHelperTest < ActionView::TestCase @firm = Firm.new() @firm.time_zone = nil - html = time_zone_select( "firm", "time_zone", nil, default: "B" ) + 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" + @@ -1250,7 +1250,7 @@ class FormOptionsHelperTest < ActionView::TestCase 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" ) + 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" + diff --git a/actionview/test/template/form_tag_helper_test.rb b/actionview/test/template/form_tag_helper_test.rb index da929cac8f..1248a0bb09 100644 --- a/actionview/test/template/form_tag_helper_test.rb +++ b/actionview/test/template/form_tag_helper_test.rb @@ -65,13 +65,13 @@ 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 @@ -694,31 +694,31 @@ class FormTagHelperTest < ActionView::TestCase def test_text_area_tag_options_symbolize_keys_side_effects 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" } 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" } 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" } 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" } label_tag "submit source", "title", options - assert_equal options, option: "random_option" + assert_equal({ option: "random_option" }, options) end def protect_against_forgery? diff --git a/actionview/test/template/javascript_helper_test.rb b/actionview/test/template/javascript_helper_test.rb index 0468c845d2..c7670b056b 100644 --- a/actionview/test/template/javascript_helper_test.rb +++ b/actionview/test/template/javascript_helper_test.rb @@ -7,7 +7,7 @@ class JavaScriptHelperTest < ActionView::TestCase 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 end @@ -18,7 +18,7 @@ class JavaScriptHelperTest < ActionView::TestCase def test_escape_javascript assert_equal "", escape_javascript(nil) assert_equal %(This \\"thing\\" is really\\n netos\\'), escape_javascript(%(This "thing" is really\n netos')) - 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!) @@ -47,8 +47,8 @@ class JavaScriptHelperTest < ActionView::TestCase # 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'></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 diff --git a/actionview/test/template/number_helper_test.rb b/actionview/test/template/number_helper_test.rb index 2a2ada2b36..678120a9c9 100644 --- a/actionview/test/template/number_helper_test.rb +++ b/actionview/test/template/number_helper_test.rb @@ -4,7 +4,7 @@ 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,7 +13,7 @@ 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") @@ -25,7 +25,7 @@ class NumberHelperTest < ActionView::TestCase 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> %") @@ -43,13 +43,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 +57,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) diff --git a/actionview/test/template/output_safety_helper_test.rb b/actionview/test/template/output_safety_helper_test.rb index 98b1938276..8691bb11ee 100644 --- a/actionview/test/template/output_safety_helper_test.rb +++ b/actionview/test/template/output_safety_helper_test.rb @@ -26,10 +26,10 @@ class OutputSafetyHelperTest < ActionView::TestCase end test "safe_join should work recursively similarly to Array.join" do - joined = safe_join(["a",["b","c"]], ":") + joined = safe_join(["a", ["b", "c"]], ":") assert_equal "a:b:c", joined - joined = safe_join(['"a"',["<b>","<c>"]], " <br/> ") + joined = safe_join(['"a"', ["<b>", "<c>"]], " <br/> ") assert_equal ""a" <br/> <b> <br/> <c>", joined end diff --git a/actionview/test/template/test_case_test.rb b/actionview/test/template/test_case_test.rb index 41225000f0..3deddd5706 100644 --- a/actionview/test/template/test_case_test.rb +++ b/actionview/test/template/test_case_test.rb @@ -50,7 +50,7 @@ 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 diff --git a/actionview/test/template/text_helper_test.rb b/actionview/test/template/text_helper_test.rb index fb557c24ac..251c98230f 100644 --- a/actionview/test/template/text_helper_test.rb +++ b/actionview/test/template/text_helper_test.rb @@ -316,7 +316,7 @@ class TextHelperTest < ActionView::TestCase 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", @@ -329,7 +329,7 @@ class TextHelperTest < ActionView::TestCase 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 @@ -463,11 +463,11 @@ class TextHelperTest < ActionView::TestCase 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 @@ -486,13 +486,13 @@ 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 diff --git a/actionview/test/template/text_test.rb b/actionview/test/template/text_test.rb index 6510688f97..ee526dc367 100644 --- a/actionview/test/template/text_test.rb +++ b/actionview/test/template/text_test.rb @@ -1,17 +1,7 @@ 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 - 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 - end - - test "formats returns string for unknown MIME type" do - assert_equal ["foo"], ActionView::Template::Text.new("", "foo").formats + test "formats always return :text" do + assert_equal [:text], ActionView::Template::Text.new("").formats end end diff --git a/actionview/test/template/url_helper_test.rb b/actionview/test/template/url_helper_test.rb index 2ef2be65d2..1e64385b52 100644 --- a/actionview/test/template/url_helper_test.rb +++ b/actionview/test/template/url_helper_test.rb @@ -221,6 +221,33 @@ class UrlHelperTest < ActiveSupport::TestCase ) end + class FakeParams + def initialize(permitted = true) + @permitted = permitted + end + + def permitted? + @permitted + end + + def to_h + { foo: :bar, baz: "quux" } + end + end + + def test_button_to_with_permited_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_unpermited_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>}, @@ -783,7 +810,7 @@ class TasksController < ActionController::Base render_default end - protected + private def render_default render inline: "<%= link_to_unless_current('tasks', tasks_path) %>\n" + "<%= link_to_unless_current('tasks', tasks_url) %>" 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..414c2063c3 --- /dev/null +++ b/actionview/test/ujs/config.ru @@ -0,0 +1,3 @@ +$LOAD_PATH.unshift File.expand_path("..", __FILE__) +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-remote-callbacks.js b/actionview/test/ujs/public/test/call-remote-callbacks.js new file mode 100644 index 0000000000..082d10bfbd --- /dev/null +++ b/actionview/test/ujs/public/test/call-remote-callbacks.js @@ -0,0 +1,469 @@ +(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('ajaxStop') + $(document).unbind('iframe:loading') + } +}) + +function start_after_submit(form) { + form.bindNative('ajax:complete', function() { + ok(true, 'ajax:complete') + start() + }) +} + +function submit(fn) { + var form = $('form') + start_after_submit(form) + + if (fn) fn(form) + form.triggerNative('submit') +} + +function submit_with_button(submit_button) { + var form = $('form') + start_after_submit(form) + + submit_button.triggerNative('click') +} + +asyncTest('modifying form fields with "ajax:before" sends modified data in request', 4, 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', 2, 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', 2, 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.unbind('ajax:complete').bindNative('ajax:complete', function() { + ok(false, 'ajax:complete should not run') + }) + form.bindNative('ajax:error', function(e, xhr, status, error) { + ok(false, 'ajax:error should not run') + }) + $(document).bindNative('ajaxStop', function() { + start() + }) + }) +}) + +asyncTest('blank required form input field should abort request and trigger "ajax:aborted:required" event', 5, function() { + $(document).bind('iframe:loading', function() { + ok(false, 'form should not get submitted') + }) + + var form = $('form[data-remote]') + .append($('<input type="text" name="user_name" required="required">')) + .append($('<textarea name="user_bio" required="required"></textarea>')) + .bindNative('ajax:beforeSend', function() { + ok(false, 'ajax:beforeSend should not run') + }) + .bindNative('ajax:aborted:required', function(e, data) { + data = $(data) + ok(data.length == 2, 'ajax:aborted:required event is passed all blank required inputs (jQuery objects)') + ok(data.first().is('input[name="user_name"]'), 'ajax:aborted:required adds blank required input to data') + ok(data.last().is('textarea[name="user_bio"]'), 'ajax:aborted:required adds blank required textarea to data') + ok(true, 'ajax:aborted:required should run') + }) + .triggerNative('submit') + + setTimeout(function() { + form.find('input[required],textarea[required]').val('Tyler') + form.unbind('ajax:beforeSend') + submit() + }, 13) +}) + +asyncTest('blank required form input for non-remote form should abort normal submission', 1, function() { + var form = $('form[data-remote]') + .append($('<input type="text" name="user_name" required="required">')) + .removeAttr('data-remote') + .bindNative('ujs:everythingStopped', function() { + ok(true, 'ujs:everythingStopped should run') + }) + .triggerNative('submit') + + setTimeout(function() { + start() + }, 13) +}) + +asyncTest('form should be submitted with blank required fields if handler is bound to "ajax:aborted:required" event that returns false', 1, function() { + var form = $('form[data-remote]') + .append($('<input type="text" name="user_name" required="required">')) + .bindNative('ajax:beforeSend', function() { + ok(true, 'ajax:beforeSend should run') + }) + .bindNative('ajax:aborted:required', function() { + return false + }) + .triggerNative('submit') + + setTimeout(function() { + start() + }, 13) +}) + +asyncTest('disabled fields should not be included in blank required check', 2, function() { + var form = $('form[data-remote]') + .append($('<input type="text" name="user_name" required="required" disabled="disabled">')) + .append($('<textarea name="user_bio" required="required" disabled="disabled"></textarea>')) + .bindNative('ajax:beforeSend', function() { + ok(true, 'ajax:beforeSend should run') + }) + .bindNative('ajax:aborted:required', function() { + ok(false, 'ajax:aborted:required should not run') + }) + + submit() +}) + +asyncTest('form should be submitted with blank required fields if it has the "novalidate" attribute', 2, function() { + var form = $('form[data-remote]') + .append($('<input type="text" name="user_name" required="required">')) + .attr('novalidate', 'novalidate') + .bindNative('ajax:beforeSend', function() { + ok(true, 'ajax:beforeSend should run') + }) + .bindNative('ajax:aborted:required', function() { + ok(false, 'ajax:aborted:required should not run') + }) + + submit() +}) + +asyncTest('form should be submitted with blank required fields if the button has the "formnovalidate" attribute', 2, function() { + var submit_button = $('<input type="submit" formnovalidate>') + var form = $('form[data-remote]') + .append($('<input type="text" name="user_name" required="required">')) + .append(submit_button) + .bindNative('ajax:beforeSend', function() { + ok(true, 'ajax:beforeSend should run') + }) + .bindNative('ajax:aborted:required', function() { + ok(false, 'ajax:aborted:required should not run') + }) + + submit_with_button(submit_button) +}) + +asyncTest('blank required form input for non-remote form with "novalidate" attribute should not abort normal submission', 1, function() { + $(document).bind('iframe:loading', function() { + ok(true, 'form should get submitted') + }) + + var form = $('form[data-remote]') + .append($('<input type="text" name="user_name" required="required">')) + .removeAttr('data-remote') + .attr('novalidate', 'novalidate') + .triggerNative('submit') + + setTimeout(function() { + start() + }, 13) +}) + +asyncTest('unchecked required checkbox should abort form submission', 1, function() { + var form = $('form[data-remote]') + .append($('<input type="checkbox" name="agree" required="required">')) + .removeAttr('data-remote') + .bindNative('ujs:everythingStopped', function() { + ok(true, 'ujs:everythingStopped should run') + }) + .triggerNative('submit') + + setTimeout(function() { + start() + }, 13) +}) + +asyncTest('unchecked required radio should abort form submission', 3, function() { + var form = $('form[data-remote]') + .append($('<input type="radio" name="yes_no_none" required="required" value=1>')) + .append($('<input type="radio" name="yes_no_none" required="required" value=2>')) + .removeAttr('data-remote') + .bindNative('ujs:everythingStopped', function() { + ok(true, 'ujs:everythingStopped should run') + }) + .bindNative('ajax:aborted:required', function(e, data) { + data = $(data) + equal(data.length, 2, 'blankRequiredInputs should include both radios') + ok(data.first().is('input[type=radio][value=1]'), 'blankRequiredInputs[0] should be the first radio') + }) + .triggerNative('submit') + + setTimeout(function() { + start() + }, 13) +}) + +asyncTest('required radio should only require one to be checked', 1, function() { + $(document).bind('iframe:loading', function() { + ok(true, 'form should get submitted') + }) + + var form = $('form[data-remote]') + .append($('<input type="radio" name="yes_no" required="required" value=1 id="checkme">')) + .append($('<input type="radio" name="yes_no" required="required" value=2>')) + .removeAttr('data-remote') + .bindNative('ujs:everythingStopped', function() { + ok(false, 'ujs:everythingStopped should not run') + }) + .find('#checkme').prop('checked', true) + .end() + .triggerNative('submit') + + setTimeout(function() { + start() + }, 13) +}) + +asyncTest('required radio should only require one to be checked if not all radios are required', 1, function() { + $(document).bind('iframe:loading', function() { + ok(true, 'form should get submitted') + }) + + var form = $('form[data-remote]') + // Check the radio that is not required + .append($('<input type="radio" name="yes_no_maybe" value=1 >')) + // Check the radio that is not required + .append($('<input type="radio" name="yes_no_maybe" value=2 id="checkme">')) + // Only one needs to be required + .append($('<input type="radio" name="yes_no_maybe" required="required" value=3>')) + .removeAttr('data-remote') + .bindNative('ujs:everythingStopped', function() { + ok(false, 'ujs:everythingStopped should not run') + }) + .find('#checkme').prop('checked', true) + .end() + .triggerNative('submit') + + setTimeout(function() { + start() + }, 13) +}) + +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.unbind('ajax:complete').bindNative('ajax:complete', function() { + ok(false, 'ajax:complete should not run') + }) + $(document).bindNative('ajaxStop', function() { + start() + }) + }) +}) + +asyncTest('"ajax:beforeSend", "ajax:send", "ajax:success" and "ajax:complete" are triggered', 9, 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') + }) + }) +}) + +if(window.phantom !== undefined) { + asyncTest('"ajax:beforeSend", "ajax:send", "ajax:error" and "ajax:complete" are triggered on error', 7, 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, xhr, status, error) { + ok(xhr.getResponseHeader, 'first argument to "ajax:error" should be an XHR object') + equal(status, 'error', 'second argument to ajax:error should be a status string') + // Firefox 8 returns "Forbidden " with trailing space + equal($.trim(error), 'Forbidden', 'third argument to ajax:error should be an HTTP status response') + // Opera returns "0" for HTTP code + equal(xhr.status, window.opera ? 0 : 403, 'status code should be 403') + }) + }) + }) +} + +// IF THIS TEST IS FAILING, TRY INCREASING THE TIMEOUT AT THE BOTTOM TO > 100 +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:complete', function() { + ok(true, 'ajax:complete handler is triggered') + }) + .delegate('form[data-remote]', 'ajax:success', function() { + ok(true, 'ajax:success handler is triggered') + }) + $('form[data-remote]').triggerNative('submit') + + setTimeout(function() { + start() + }, 63) +}) + +asyncTest('binding to ajax:send event to call jquery methods on ajax object', 2, function() { + $('form[data-remote]') + .bindNative('ajax:send', function(e, xhr) { + ok(true, 'event should fire') + equal(typeof(xhr.abort), 'function', 'event should pass jqXHR object') + xhr.abort() + }) + .triggerNative('submit') + + setTimeout(function() { start() }, 35) +}) + +})() 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..dbeb8ad832 --- /dev/null +++ b/actionview/test/ujs/public/test/call-remote.js @@ -0,0 +1,247 @@ +(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('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..28190c2250 --- /dev/null +++ b/actionview/test/ujs/public/test/data-confirm.js @@ -0,0 +1,288 @@ +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?' + })) + + 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') +}) 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..a51aa10417 --- /dev/null +++ b/actionview/test/ujs/public/test/data-remote.js @@ -0,0 +1,400 @@ +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') + console.log(data.params) + 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() { + $('form') + .append( + $('<select />', { + 'name': 'user_data', + 'data-remote': 'true', + 'data-params': 'data1=value1', + 'data-url': '/echo' + }) + .append($('<option />', {value: 'optionValue1', text: 'option1'})) + .append($('<option />', {value: 'optionValue2', text: 'option2'})) + ) + + $('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', 5, function() { + $('#qunit-fixture') + .append($('<input type="text" name="user_data" value="value1" 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') + 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() { + $('form') + .append( + $('<select />', { + 'name': 'user_data', + 'data-remote': 'false', + 'data-params': 'data1=value1', + 'data-url': '/echo' + }) + .append($('<option />', {value: 'optionValue1', text: 'option1'})) + .append($('<option />', {value: 'optionValue2', text: 'option2'})) + ) + + $('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') +}) diff --git a/actionview/test/ujs/public/test/override.js b/actionview/test/ujs/public/test/override.js new file mode 100644 index 0000000000..be6ec7749b --- /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 jquery-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..3375456f11 --- /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 an 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.metadata.js b/actionview/test/ujs/public/vendor/jquery.metadata.js new file mode 100644 index 0000000000..ad8bfba404 --- /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 contianing 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..0e279fde17 --- /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 http://es5.github.com/#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..25f70baf5f --- /dev/null +++ b/actionview/test/ujs/server.rb @@ -0,0 +1,105 @@ +require "rails" +require "action_controller/railtie" +require "action_view/railtie" +require "blade" +require "json" + +JQUERY_VERSIONS = %w[ 1.8.0 1.8.1 1.8.2 1.8.3 1.9.0 1.9.1 1.10.0 1.10.1 1.10.2 1.11.0 2.0.0 2.1.0].freeze + +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 jquery_link(version) + if params[:version] == version + "[#{version}]" + else + "<a href='/?version=#{version}&cdn=#{params[:cdn]}'>#{version}</a>".html_safe + end + end + + def cdn_link(cdn) + if params[:cdn] == cdn + "[#{cdn}]" + else + "<a href='/?version=#{params[:version]}&cdn=#{cdn}'>#{cdn}</a>".html_safe + end + end + + def jquery_src + if params[:version] == "edge" + "/vendor/jquery.js" + elsif params[:cdn] && params[:cdn] == "googleapis" + "https://ajax.googleapis.com/ajax/libs/jquery/#{params[:version]}/jquery.min.js" + else + "http://code.jquery.com/jquery-#{params[:version]}.js" + end + end + + 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 + + def jquery_versions + JQUERY_VERSIONS + end +end + +class TestsController < ActionController::Base + helper TestsHelper + layout "application" + + def index + params[:version] ||= ENV["JQUERY_VERSION"] || "1.11.0" + params[:cdn] ||= "jquery" + 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..74fa3bd06d --- /dev/null +++ b/actionview/test/ujs/views/layouts/application.html.erb @@ -0,0 +1,40 @@ +<!DOCTYPE html> +<html id="html"> + <head> + <title><%= @title %></title> + <link href="/vendor/qunit.css" media="screen" rel="stylesheet" type="text/css" media="screen, projection" /> + <style> + #jquery-cdn, #jquery-version { + padding: 0 2em .8em 0; + text-align: right; + font-family: sans-serif; + line-height: 1; + color: #8699A4; + background-color: #0d3349; + } + #jquery-cdn a, #jquery-version a { + color: white; + text-decoration: underline; + } + </style> + + <%= script_tag jquery_src %> + <script> + // This is for test in override.js. + // Must go after jQuery is loaded, but before jquery-ujs. + $(document).bind('rails:attachBindings', function() { + $.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 + $.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..393a5ee235 --- /dev/null +++ b/actionview/test/ujs/views/tests/index.html.erb @@ -0,0 +1,25 @@ +<% @title = "jquery-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' %> + +<h1 id="qunit-header"><%= @title %></h1> +<div id="jquery-cdn"> + CDN: + <%= cdn_link 'jquery' %> β’ + <%= cdn_link 'googleapis' %> +</div> +<div id="jquery-version"> + jQuery version: + + <% jquery_versions.each do |v| %> + <%= ' β’ ' if v != jquery_versions.first %> + <%= jquery_link v %> + <% end %> + <%= (' β’ ' + jquery_link('edge')) if File.exist?(Rails.root + '/public/vendor/jquery.js') %> +</div> +<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> |