|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require 'test_helper' |
| 4 | + |
| 5 | +describe SchemaType do |
| 6 | + before do |
| 7 | + skip 'PostgreSQL only' unless postgresql? |
| 8 | + end |
| 9 | + |
| 10 | + def assert_lineage(parent, child) |
| 11 | + assert_equal parent, child.parent |
| 12 | + assert_equal [child, parent], child.self_and_ancestors |
| 13 | + |
| 14 | + # make sure reloading doesn't affect the self_and_ancestors: |
| 15 | + child.reload |
| 16 | + assert_equal [child, parent], child.self_and_ancestors |
| 17 | + end |
| 18 | + |
| 19 | + it 'properly handles schema-qualified table names' do |
| 20 | + assert_equal 'test_schema.schema_types', SchemaType.table_name |
| 21 | + assert_equal 'test_schema.schema_type_hierarchies', SchemaTypeHierarchy.table_name |
| 22 | + end |
| 23 | + |
| 24 | + it 'finds self and parents when children << is used' do |
| 25 | + parent = SchemaType.new(name: 'Electronics') |
| 26 | + child = SchemaType.new(name: 'Phones') |
| 27 | + parent.children << child |
| 28 | + parent.save |
| 29 | + assert_lineage(parent, child) |
| 30 | + end |
| 31 | + |
| 32 | + it 'finds self and parents properly if the constructor is used' do |
| 33 | + parent = SchemaType.create(name: 'Electronics') |
| 34 | + child = SchemaType.create(name: 'Phones', parent: parent) |
| 35 | + assert_lineage(parent, child) |
| 36 | + end |
| 37 | + |
| 38 | + it 'creates hierarchy records in the schema-qualified table' do |
| 39 | + parent = SchemaType.create!(name: 'Electronics') |
| 40 | + child = SchemaType.create!(name: 'Phones', parent: parent) |
| 41 | + |
| 42 | + hierarchy = SchemaTypeHierarchy.where(ancestor_id: parent.id, descendant_id: child.id).first |
| 43 | + refute_nil hierarchy |
| 44 | + assert_equal 1, hierarchy.generations |
| 45 | + end |
| 46 | + |
| 47 | + it 'fixes self_and_ancestors properly on reparenting' do |
| 48 | + a = SchemaType.create! name: 'Electronics' |
| 49 | + b = SchemaType.create! name: 'Phones' |
| 50 | + assert_equal([b], b.self_and_ancestors.to_a) |
| 51 | + a.children << b |
| 52 | + assert_equal([b, a], b.self_and_ancestors.to_a) |
| 53 | + end |
| 54 | + |
| 55 | + it 'supports tree operations with schema-qualified tables' do |
| 56 | + root = SchemaType.create!(name: 'Electronics') |
| 57 | + child1 = SchemaType.create!(name: 'Computers', parent: root) |
| 58 | + child2 = SchemaType.create!(name: 'Phones', parent: root) |
| 59 | + grandchild = SchemaType.create!(name: 'Laptops', parent: child1) |
| 60 | + |
| 61 | + assert_equal 2, root.children.count |
| 62 | + assert_equal 1, child1.children.count |
| 63 | + assert_equal 0, child2.children.count |
| 64 | + assert_equal [grandchild, child1, root], grandchild.self_and_ancestors |
| 65 | + assert_equal [root, child1, child2, grandchild], root.self_and_descendants.order(:name) |
| 66 | + end |
| 67 | +end |
0 commit comments