# frozen_string_literal: true require 'test_helper' module Upgrow class BasicModelTest < ActiveSupport::TestCase class SampleModel < BasicModel attribute :title attribute :body belongs_to :user end class SubSampleModel < SampleModel has_many :tags end setup do @original_schema = BasicModel.schema.dup end teardown do BasicModel.schema = @original_schema end test '.schema includes ID by default' do assert_equal [:id, :title, :body], SampleModel.schema.attribute_names end test '.schema does not have associations by default' do assert_empty BasicModel.schema.association_names end test '.schema includes the Model associations' do assert_equal [:user], SampleModel.schema.association_names assert_equal [:user, :tags], SubSampleModel.schema.association_names end test '.has_many defines an association in the Schema' do BasicModel.has_many(:comments) assert_equal [:comments], BasicModel.schema.association_names end test '.belongs_to defines an association in the Schema' do BasicModel.belongs_to(:author) assert_equal [:author], BasicModel.schema.association_names end test '.new requires all attributes' do error = assert_raises(KeyError) do SampleModel.new(title: 'volmer', id: 1) end assert_equal 'key not found: :body', error.message end test '.new optionally accepts associations' do model = SampleModel.new( title: 'volmer', body: 'My long body', id: 1, user: :my_user ) assert_equal :my_user, model.user end test '#respond_to? is true for association readers' do model = SubSampleModel.new(id: 1, title: 'volmer', body: 'hello') assert model.respond_to?(:user) assert model.respond_to?(:tags) end test 'association reader raises Association Not Loaded Error for an association that was not loaded' do model = SampleModel.new( title: 'volmer', body: 'My long body', id: 1 ) error = assert_raises(Model::AssociationNotLoadedError) { model.user } message = 'Association user not loaded for ' \ 'Upgrow::BasicModelTest::SampleModel.' assert_equal message, error.message end test 'attribute readers work when association is not loaded' do model = SampleModel.new( title: 'volmer', body: 'My long body', id: 1 ) assert_equal 'volmer', model.title end end end