From b26338e83b4249ede5ea1368498b4dbf31b44612 Mon Sep 17 00:00:00 2001 From: claudiob Date: Fri, 19 Dec 2014 12:49:50 -0800 Subject: [PATCH] Better tests for AV::RecordIdentifier This commit intends to clarify the scope of ActionView::RecordIdentifier methods `dom_id` and `dom_class`. Most of the current documentation comes from da257eb8 (7 years ago) when the decoupling of ActionView, ActiveRecord and ActiveModel was not a concern. Since then, steps have been taken to reach such decoupling. Therefore I think it's important to show that ActionView::RecordIdentifier **does not strictly depend on the ActiveRecord API**: any class `Post` implementing `post.to_key` and `post.model_name.param_key` will work. This commit adds a test to prove that ActionView::RecordIdentifier methods can also be used on objects that do not subclass ActiveRecord::Base. --- actionview/test/lib/controller/fake_models.rb | 12 ++++++ .../test/template/record_identifier_test.rb | 43 +++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/actionview/test/lib/controller/fake_models.rb b/actionview/test/lib/controller/fake_models.rb index cb02a56cb4..789b1d198b 100644 --- a/actionview/test/lib/controller/fake_models.rb +++ b/actionview/test/lib/controller/fake_models.rb @@ -170,3 +170,15 @@ end class Car < Struct.new(:color) end + +class Plane + attr_reader :to_key + + def model_name + OpenStruct.new param_key: 'airplane' + end + + def save + @to_key = [1] + end +end diff --git a/actionview/test/template/record_identifier_test.rb b/actionview/test/template/record_identifier_test.rb index f8ee563469..04898c0b0e 100644 --- a/actionview/test/template/record_identifier_test.rb +++ b/actionview/test/template/record_identifier_test.rb @@ -46,3 +46,46 @@ class RecordIdentifierTest < ActiveSupport::TestCase assert_equal @singular, ActionView::RecordIdentifier.dom_class(@record) end end + +class RecordIdentifierWithoutActiveModelTest < ActiveSupport::TestCase + include ActionView::RecordIdentifier + + def setup + @record = Plane.new + end + + def test_dom_id_with_new_record + assert_equal "new_airplane", dom_id(@record) + end + + def test_dom_id_with_new_record_and_prefix + assert_equal "custom_prefix_airplane", dom_id(@record, :custom_prefix) + end + + def test_dom_id_with_saved_record + @record.save + assert_equal "airplane_1", dom_id(@record) + end + + def test_dom_id_with_prefix + @record.save + assert_equal "edit_airplane_1", dom_id(@record, :edit) + end + + def test_dom_class + assert_equal 'airplane', dom_class(@record) + end + + def test_dom_class_with_prefix + assert_equal "custom_prefix_airplane", dom_class(@record, :custom_prefix) + end + + def test_dom_id_as_singleton_method + @record.save + assert_equal "airplane_1", ActionView::RecordIdentifier.dom_id(@record) + end + + def test_dom_class_as_singleton_method + assert_equal 'airplane', ActionView::RecordIdentifier.dom_class(@record) + end +end