# frozen_string_literal: true require "cases/helper" require "models/person" require "models/topic" require "pp" class NonExistentTable < ActiveRecord::Base; end class CoreTest < ActiveRecord::TestCase fixtures :topics def test_inspect_class assert_equal "ActiveRecord::Base", ActiveRecord::Base.inspect assert_equal "LoosePerson(abstract)", LoosePerson.inspect assert_match(/^Topic\(id: integer, title: string/, Topic.inspect) end def test_inspect_instance topic = topics(:first) assert_equal %(#), topic.inspect end def test_inspect_instance_with_lambda_date_formatter before = Time::DATE_FORMATS[:inspect] Time::DATE_FORMATS[:inspect] = ->(date) { "my_format" } topic = topics(:first) assert_equal %(#), topic.inspect ensure Time::DATE_FORMATS[:inspect] = before end def test_inspect_new_instance assert_match(/Topic id: nil/, Topic.new.inspect) end def test_inspect_limited_select_instance assert_equal %(#), Topic.all.merge!(select: "id", where: "id = 1").first.inspect assert_equal %(#), Topic.all.merge!(select: "id, title", where: "id = 1").first.inspect end def test_inspect_instance_with_non_primary_key_id_attribute topic = topics(:first).becomes(TitlePrimaryKeyTopic) assert_match(/id: 1/, topic.inspect) end def test_inspect_class_without_table assert_equal "NonExistentTable(Table doesn't exist)", NonExistentTable.inspect end def test_pretty_print_new topic = Topic.new actual = +"" PP.pp(topic, StringIO.new(actual)) expected = <<~PRETTY # PRETTY assert actual.start_with?(expected.split("XXXXXX").first) assert actual.end_with?(expected.split("XXXXXX").last) end def test_pretty_print_persisted topic = topics(:first) actual = +"" PP.pp(topic, StringIO.new(actual)) expected = <<~PRETTY #]+> PRETTY assert_match(/\A#{expected}\z/, actual) end def test_pretty_print_uninitialized topic = Topic.allocate actual = +"" PP.pp(topic, StringIO.new(actual)) expected = "#\n" assert actual.start_with?(expected.split("XXXXXX").first) assert actual.end_with?(expected.split("XXXXXX").last) end def test_pretty_print_overridden_by_inspect subtopic = Class.new(Topic) do def inspect "inspecting topic" end end actual = +"" PP.pp(subtopic.new, StringIO.new(actual)) assert_equal "inspecting topic\n", actual end def test_pretty_print_with_non_primary_key_id_attribute topic = topics(:first).becomes(TitlePrimaryKeyTopic) actual = +"" PP.pp(topic, StringIO.new(actual)) assert_match(/id: 1/, actual) end end