fixtures_test.rb 24.3 KB
Newer Older
1 2 3
require 'cases/helper'
require 'models/admin'
require 'models/admin/account'
4
require 'models/admin/randomly_named_c1'
5
require 'models/admin/user'
J
Jeremy Kemper 已提交
6
require 'models/binary'
7 8 9
require 'models/book'
require 'models/category'
require 'models/company'
J
Jeremy Kemper 已提交
10
require 'models/computer'
11
require 'models/course'
J
Jeremy Kemper 已提交
12 13
require 'models/developer'
require 'models/joke'
14
require 'models/matey'
J
Jeremy Kemper 已提交
15 16
require 'models/parrot'
require 'models/pirate'
17
require 'models/post'
18
require 'models/randomly_named_c1'
19
require 'models/reply'
20
require 'models/ship'
21 22 23 24
require 'models/task'
require 'models/topic'
require 'models/traffic_light'
require 'models/treasure'
25
require 'tempfile'
D
Initial  
David Heinemeier Hansson 已提交
26

27
class FixturesTest < ActiveRecord::TestCase
28 29 30
  self.use_instantiated_fixtures = true
  self.use_transactional_fixtures = false

31
  # other_topics fixture should not be included here
P
Pratik Naik 已提交
32
  fixtures :topics, :developers, :accounts, :tasks, :categories, :funny_jokes, :binaries, :traffic_lights
33

34
  FIXTURES = %w( accounts binaries companies customers
D
Initial  
David Heinemeier Hansson 已提交
35
                 developers developers_projects entrants
36
                 movies projects subscribers topics tasks )
37
  MATCH_ATTRIBUTE_NAME = /[a-zA-Z][-\w]*/
D
Initial  
David Heinemeier Hansson 已提交
38 39 40 41

  def test_clean_fixtures
    FIXTURES.each do |name|
      fixtures = nil
42
      assert_nothing_raised { fixtures = create_fixtures(name).first }
J
Jason Noble 已提交
43
      assert_kind_of(ActiveRecord::Fixtures, fixtures)
44
      fixtures.each { |_name, fixture|
D
Initial  
David Heinemeier Hansson 已提交
45 46 47 48 49 50 51
        fixture.each { |key, value|
          assert_match(MATCH_ATTRIBUTE_NAME, key)
        }
      }
    end
  end

52 53
  def test_broken_yaml_exception
    badyaml = Tempfile.new ['foo', '.yml']
54
    badyaml.write 'a: : '
55 56 57
    badyaml.flush

    dir  = File.dirname badyaml.path
58
    name = File.basename badyaml.path, '.yml'
59 60 61 62 63 64 65 66
    assert_raises(ActiveRecord::Fixture::FormatError) do
      ActiveRecord::Fixtures.create_fixtures(dir, name)
    end
  ensure
    badyaml.close
    badyaml.unlink
  end

67
  def test_create_fixtures
J
Jason Noble 已提交
68
    ActiveRecord::Fixtures.create_fixtures(FIXTURES_ROOT, "parrots")
69 70 71
    assert Parrot.find_by_name('Curious George'), 'George is in the database'
  end

D
Initial  
David Heinemeier Hansson 已提交
72 73 74 75
  def test_multiple_clean_fixtures
    fixtures_array = nil
    assert_nothing_raised { fixtures_array = create_fixtures(*FIXTURES) }
    assert_kind_of(Array, fixtures_array)
J
Jason Noble 已提交
76
    fixtures_array.each { |fixtures| assert_kind_of(ActiveRecord::Fixtures, fixtures) }
D
Initial  
David Heinemeier Hansson 已提交
77 78 79
  end

  def test_attributes
80
    topics = create_fixtures("topics").first
D
Initial  
David Heinemeier Hansson 已提交
81 82 83 84 85
    assert_equal("The First Topic", topics["first"]["title"])
    assert_nil(topics["second"]["author_email_address"])
  end

  def test_inserts
A
Aaron Patterson 已提交
86
    create_fixtures("topics")
87 88
    first_row = ActiveRecord::Base.connection.select_one("SELECT * FROM topics WHERE author_name = 'David'")
    assert_equal("The First Topic", first_row["title"])
D
Initial  
David Heinemeier Hansson 已提交
89

90 91
    second_row = ActiveRecord::Base.connection.select_one("SELECT * FROM topics WHERE author_name = 'Mary'")
    assert_nil(second_row["author_email_address"])
D
Initial  
David Heinemeier Hansson 已提交
92 93
  end

94 95
  if ActiveRecord::Base.connection.supports_migrations?
    def test_inserts_with_pre_and_suffix
96
      # Reset cache to make finds on the new table work
J
Jason Noble 已提交
97
      ActiveRecord::Fixtures.reset_cache
98

99
      ActiveRecord::Base.connection.create_table :prefix_other_topics_suffix do |t|
100 101 102 103 104 105
        t.column :title, :string
        t.column :author_name, :string
        t.column :author_email_address, :string
        t.column :written_on, :datetime
        t.column :bonus_time, :time
        t.column :last_read, :date
106
        t.column :content, :string
107 108 109 110 111 112 113 114 115 116 117 118 119 120
        t.column :approved, :boolean, :default => true
        t.column :replies_count, :integer, :default => 0
        t.column :parent_id, :integer
        t.column :type, :string, :limit => 50
      end

      # Store existing prefix/suffix
      old_prefix = ActiveRecord::Base.table_name_prefix
      old_suffix = ActiveRecord::Base.table_name_suffix

      # Set a prefix/suffix we can test against
      ActiveRecord::Base.table_name_prefix = 'prefix_'
      ActiveRecord::Base.table_name_suffix = '_suffix'

121 122 123 124 125
      other_topic_klass = Class.new(ActiveRecord::Base) do
        def self.name
          "OtherTopic"
        end
      end
126

127
      topics = [create_fixtures("other_topics")].flatten.first
128

129 130 131
      # This checks for a caching problem which causes a bug in the fixtures
      # class-level configuration helper.
      assert_not_nil topics, "Fixture data inserted, but fixture objects not returned from create"
132 133 134 135 136 137 138 139 140 141 142 143 144

      first_row = ActiveRecord::Base.connection.select_one("SELECT * FROM prefix_other_topics_suffix WHERE author_name = 'David'")
      assert_not_nil first_row, "The prefix_other_topics_suffix table appears to be empty despite create_fixtures: the row with author_name = 'David' was not found"
      assert_equal("The First Topic", first_row["title"])

      second_row = ActiveRecord::Base.connection.select_one("SELECT * FROM prefix_other_topics_suffix WHERE author_name = 'Mary'")
      assert_nil(second_row["author_email_address"])

      assert_equal :prefix_other_topics_suffix, topics.table_name.to_sym
      # This assertion should preferably be the last in the list, because calling
      # other_topic_klass.table_name sets a class-level instance variable
      assert_equal :prefix_other_topics_suffix, other_topic_klass.table_name.to_sym

145
    ensure
146
      # Restore prefix/suffix to its previous values
147 148
      ActiveRecord::Base.table_name_prefix = old_prefix
      ActiveRecord::Base.table_name_suffix = old_suffix
149

150
      ActiveRecord::Base.connection.drop_table :prefix_other_topics_suffix rescue nil
151 152 153
    end
  end

154
  def test_insert_with_datetime
A
Aaron Patterson 已提交
155
    create_fixtures("tasks")
156 157 158 159
    first = Task.find(1)
    assert first
  end

D
Initial  
David Heinemeier Hansson 已提交
160 161 162 163 164
  def test_logger_level_invariant
    level = ActiveRecord::Base.logger.level
    create_fixtures('topics')
    assert_equal level, ActiveRecord::Base.logger.level
  end
165

D
Initial  
David Heinemeier Hansson 已提交
166
  def test_instantiation
167
    topics = create_fixtures("topics").first
D
Initial  
David Heinemeier Hansson 已提交
168 169
    assert_kind_of Topic, topics["first"].find
  end
170

D
Initial  
David Heinemeier Hansson 已提交
171 172 173
  def test_complete_instantiation
    assert_equal "The First Topic", @first.title
  end
174

D
Initial  
David Heinemeier Hansson 已提交
175 176 177 178
  def test_fixtures_from_root_yml_with_instantiation
    # assert_equal 2, @accounts.size
    assert_equal 50, @unknown.credit_limit
  end
179

D
Initial  
David Heinemeier Hansson 已提交
180 181 182
  def test_erb_in_fixtures
    assert_equal "fixture_5", @dev_5.name
  end
183 184

  def test_empty_yaml_fixture
J
Jason Noble 已提交
185
    assert_not_nil ActiveRecord::Fixtures.new( Account.connection, "accounts", 'Account', FIXTURES_ROOT + "/naked/yml/accounts")
186 187 188
  end

  def test_empty_yaml_fixture_with_a_comment_in_it
J
Jason Noble 已提交
189
    assert_not_nil ActiveRecord::Fixtures.new( Account.connection, "companies", 'Company', FIXTURES_ROOT + "/naked/yml/companies")
190 191
  end

192 193 194 195 196 197
  def test_nonexistent_fixture_file
    nonexistent_fixture_path = FIXTURES_ROOT + "/imnothere"

    #sanity check to make sure that this file never exists
    assert Dir[nonexistent_fixture_path+"*"].empty?

198
    assert_raise(Errno::ENOENT) do
J
Jason Noble 已提交
199
      ActiveRecord::Fixtures.new( Account.connection, "companies", 'Company', nonexistent_fixture_path)
200 201 202
    end
  end

203
  def test_dirty_dirty_yaml_file
J
Jason Noble 已提交
204 205
    assert_raise(ActiveRecord::Fixture::FormatError) do
      ActiveRecord::Fixtures.new( Account.connection, "courses", 'Course', FIXTURES_ROOT + "/naked/yml/courses")
206 207 208
    end
  end

209 210
  def test_omap_fixtures
    assert_nothing_raised do
J
Jason Noble 已提交
211
      fixtures = ActiveRecord::Fixtures.new(Account.connection, 'categories', 'Category', FIXTURES_ROOT + "/categories_ordered")
212

213
      fixtures.each.with_index do |(name, fixture), i|
214 215 216 217
        assert_equal "fixture_no_#{i}", name
        assert_equal "Category #{i}", fixture['name']
      end
    end
218
  end
219 220

  def test_yml_file_in_subdirectory
D
David Heinemeier Hansson 已提交
221 222
    assert_equal(categories(:sub_special_1).name, "A special category in a subdir file")
    assert_equal(categories(:sub_special_1).class, SpecialCategory)
223 224 225
  end

  def test_subsubdir_file_with_arbitrary_name
D
David Heinemeier Hansson 已提交
226 227
    assert_equal(categories(:sub_special_3).name, "A special category in an arbitrarily named subsubdir file")
    assert_equal(categories(:sub_special_3).class, SpecialCategory)
228 229
  end

230
  def test_binary_in_fixtures
R
Rob 已提交
231
    data = File.open(ASSETS_ROOT + "/flowers.jpg", 'rb') { |f| f.read }
232
    data.force_encoding('ASCII-8BIT')
233
    data.freeze
234 235
    assert_equal data, @flowers.data
  end
P
Pratik Naik 已提交
236 237 238 239

  def test_serialized_fixtures
    assert_equal ["Green", "Red", "Orange"], traffic_lights(:uk).state
  end
J
Jeremy Kemper 已提交
240 241 242
end

if Account.connection.respond_to?(:reset_pk_sequence!)
243
  class FixturesResetPkSequenceTest < ActiveRecord::TestCase
J
Jeremy Kemper 已提交
244
    fixtures :accounts
245
    fixtures :companies
246

247 248
    def setup
      @instances = [Account.new(:credit_limit => 50), Company.new(:name => 'RoR Consulting')]
J
Jason Noble 已提交
249
      ActiveRecord::Fixtures.reset_cache # make sure tables get reinitialized
250 251 252 253 254 255 256
    end

    def test_resets_to_min_pk_with_specified_pk_and_sequence
      @instances.each do |instance|
        model = instance.class
        model.delete_all
        model.connection.reset_pk_sequence!(model.table_name, model.primary_key, model.sequence_name)
257

258 259 260
        instance.save!
        assert_equal 1, instance.id, "Sequence reset for #{model.table_name} failed."
      end
261 262
    end

263 264 265 266 267 268 269 270
    def test_resets_to_min_pk_with_default_pk_and_sequence
      @instances.each do |instance|
        model = instance.class
        model.delete_all
        model.connection.reset_pk_sequence!(model.table_name)

        instance.save!
        assert_equal 1, instance.id, "Sequence reset for #{model.table_name} failed."
271
      end
272
    end
273

274
    def test_create_fixtures_resets_sequences_when_not_cached
275
      @instances.each do |instance|
276
        max_id = create_fixtures(instance.class.table_name).first.fixtures.inject(0) do |_max_id, (_, fixture)|
277
          fixture_id = fixture['id'].to_i
278
          fixture_id > _max_id ? fixture_id : _max_id
279 280 281 282 283 284
        end

        # Clone the last fixture to check that it gets the next greatest id.
        instance.save!
        assert_equal max_id + 1, instance.id, "Sequence reset for #{instance.class.table_name} failed."
      end
285
    end
286
  end
287 288
end

289
class FixturesWithoutInstantiationTest < ActiveRecord::TestCase
290 291 292 293
  self.use_instantiated_fixtures = false
  fixtures :topics, :developers, :accounts

  def test_without_complete_instantiation
294 295 296 297
    assert !defined?(@first)
    assert !defined?(@topics)
    assert !defined?(@developers)
    assert !defined?(@accounts)
298 299 300
  end

  def test_fixtures_from_root_yml_without_instantiation
301
    assert !defined?(@unknown), "@unknown is not defined"
302
  end
303

304 305 306 307
  def test_visibility_of_accessor_method
    assert_equal false, respond_to?(:topics, false), "should be private method"
    assert_equal true, respond_to?(:topics, true), "confirm to respond surely"
  end
308 309 310 311 312 313

  def test_accessor_methods
    assert_equal "The First Topic", topics(:first).title
    assert_equal "Jamis", developers(:jamis).name
    assert_equal 50, accounts(:signals37).credit_limit
  end
314 315 316 317 318 319

  def test_accessor_methods_with_multiple_args
    assert_equal 2, topics(:first, :second).size
    assert_raise(StandardError) { topics([:first, :second]) }
  end

320 321 322 323
  def test_reloading_fixtures_through_accessor_methods
    assert_equal "The First Topic", topics(:first).title
    @loaded_fixtures['topics']['first'].expects(:find).returns(stub(:title => "Fresh Topic!"))
    assert_equal "Fresh Topic!", topics(:first, true).title
324
  end
325 326
end

327
class FixturesWithoutInstanceInstantiationTest < ActiveRecord::TestCase
328
  self.use_instantiated_fixtures = true
329
  self.use_instantiated_fixtures = :no_instances
330

331 332 333
  fixtures :topics, :developers, :accounts

  def test_without_instance_instantiation
334
    assert !defined?(@first), "@first is not defined"
335 336 337
  end
end

338
class TransactionalFixturesTest < ActiveRecord::TestCase
339
  self.use_instantiated_fixtures = true
340
  self.use_transactional_fixtures = true
341

342 343 344 345 346 347 348 349 350 351
  fixtures :topics

  def test_destroy
    assert_not_nil @first
    @first.destroy
  end

  def test_destroy_just_kidding
    assert_not_nil @first
  end
352
end
353

354
class MultipleFixturesTest < ActiveRecord::TestCase
355 356 357 358
  fixtures :topics
  fixtures :developers, :accounts

  def test_fixture_table_names
359
    assert_equal %w(topics developers accounts), fixture_table_names
360 361 362
  end
end

363
class SetupTest < ActiveRecord::TestCase
364
  # fixtures :topics
J
Jeremy Kemper 已提交
365

366 367 368
  def setup
    @first = true
  end
J
Jeremy Kemper 已提交
369

370 371 372 373 374 375 376 377 378
  def test_nothing
  end
end

class SetupSubclassTest < SetupTest
  def setup
    super
    @second = true
  end
J
Jeremy Kemper 已提交
379

380 381 382 383 384 385 386
  def test_subclassing_should_preserve_setups
    assert @first
    assert @second
  end
end


387
class OverlappingFixturesTest < ActiveRecord::TestCase
388 389 390 391
  fixtures :topics, :developers
  fixtures :developers, :accounts

  def test_fixture_table_names
392
    assert_equal %w(topics developers accounts), fixture_table_names
393 394
  end
end
395

396
class ForeignKeyFixturesTest < ActiveRecord::TestCase
397 398 399 400 401 402 403 404 405 406 407 408 409 410
  fixtures :fk_test_has_pk, :fk_test_has_fk

  # if foreign keys are implemented and fixtures
  # are not deleted in reverse order then this test
  # case will raise StatementInvalid

  def test_number1
    assert true
  end

  def test_number2
    assert true
  end
end
411

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
class OverRideFixtureMethodTest < ActiveRecord::TestCase
  fixtures :topics

  def topics(name)
    topic = super
    topic.title = 'omg'
    topic
  end

  def test_fixture_methods_can_be_overridden
    x = topics :first
    assert_equal 'omg', x.title
  end
end

427
class CheckSetTableNameFixturesTest < ActiveRecord::TestCase
428 429
  set_fixture_class :funny_jokes => 'Joke'
  fixtures :funny_jokes
430
  # Set to false to blow away fixtures cache and ensure our fixtures are loaded
431 432
  # and thus takes into account our set_fixture_class
  self.use_transactional_fixtures = false
433

434 435 436 437
  def test_table_method
    assert_kind_of Joke, funny_jokes(:a_joke)
  end
end
438

439 440 441
class FixtureNameIsNotTableNameFixturesTest < ActiveRecord::TestCase
  set_fixture_class :items => Book
  fixtures :items
442
  # Set to false to blow away fixtures cache and ensure our fixtures are loaded
443 444 445 446 447 448 449 450 451 452 453
  # and thus takes into account our set_fixture_class
  self.use_transactional_fixtures = false

  def test_named_accessor
    assert_kind_of Book, items(:dvd)
  end
end

class FixtureNameIsNotTableNameMultipleFixturesTest < ActiveRecord::TestCase
  set_fixture_class :items => Book, :funny_jokes => Joke
  fixtures :items, :funny_jokes
454
  # Set to false to blow away fixtures cache and ensure our fixtures are loaded
455 456 457 458 459 460 461 462 463 464 465 466
  # and thus takes into account our set_fixture_class
  self.use_transactional_fixtures = false

  def test_named_accessor_of_differently_named_fixture
    assert_kind_of Book, items(:dvd)
  end

  def test_named_accessor_of_same_named_fixture
    assert_kind_of Joke, funny_jokes(:a_joke)
  end
end

467
class CustomConnectionFixturesTest < ActiveRecord::TestCase
468 469
  set_fixture_class :courses => Course
  fixtures :courses
470
  self.use_transactional_fixtures = false
471

472 473 474 475
  def test_connection
    assert_kind_of Course, courses(:ruby)
    assert_equal Course.connection, courses(:ruby).connection
  end
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499

  def test_leaky_destroy
    assert_nothing_raised { courses(:ruby) }
    courses(:ruby).destroy
  end

  def test_it_twice_in_whatever_order_to_check_for_fixture_leakage
    test_leaky_destroy
  end
end

class TransactionalFixturesOnCustomConnectionTest < ActiveRecord::TestCase
  set_fixture_class :courses => Course
  fixtures :courses
  self.use_transactional_fixtures = true

  def test_leaky_destroy
    assert_nothing_raised { courses(:ruby) }
    courses(:ruby).destroy
  end

  def test_it_twice_in_whatever_order_to_check_for_fixture_leakage
    test_leaky_destroy
  end
500 501
end

502
class InvalidTableNameFixturesTest < ActiveRecord::TestCase
503
  fixtures :funny_jokes
504
  # Set to false to blow away fixtures cache and ensure our fixtures are loaded
505 506
  # and thus takes into account our lack of set_fixture_class
  self.use_transactional_fixtures = false
507 508

  def test_raises_error
509
    assert_raise FixtureClassNotFound do
510 511 512 513
      funny_jokes(:a_joke)
    end
  end
end
514

515
class CheckEscapedYamlFixturesTest < ActiveRecord::TestCase
516 517
  set_fixture_class :funny_jokes => 'Joke'
  fixtures :funny_jokes
518
  # Set to false to blow away fixtures cache and ensure our fixtures are loaded
519 520
  # and thus takes into account our set_fixture_class
  self.use_transactional_fixtures = false
521 522 523 524 525 526

  def test_proper_escaped_fixture
    assert_equal "The \\n Aristocrats\nAte the candy\n", funny_jokes(:another_joke).name
  end
end

527
class DevelopersProject; end
528
class ManyToManyFixturesWithClassDefined < ActiveRecord::TestCase
529
  fixtures :developers_projects
530

531 532 533
  def test_this_should_run_cleanly
    assert true
  end
534 535
end

536
class FixturesBrokenRollbackTest < ActiveRecord::TestCase
537 538 539
  def blank_setup
    @fixture_connections = [ActiveRecord::Base.connection]
  end
540 541
  alias_method :ar_setup_fixtures, :setup_fixtures
  alias_method :setup_fixtures, :blank_setup
542 543 544
  alias_method :setup, :blank_setup

  def blank_teardown; end
545 546
  alias_method :ar_teardown_fixtures, :teardown_fixtures
  alias_method :teardown_fixtures, :blank_teardown
547 548 549
  alias_method :teardown, :blank_teardown

  def test_no_rollback_in_teardown_unless_transaction_active
550
    assert_equal 0, ActiveRecord::Base.connection.open_transactions
551
    assert_raise(RuntimeError) { ar_setup_fixtures }
552
    assert_equal 0, ActiveRecord::Base.connection.open_transactions
553
    assert_nothing_raised { ar_teardown_fixtures }
554
    assert_equal 0, ActiveRecord::Base.connection.open_transactions
555 556 557 558 559 560 561
  end

  private
    def load_fixtures
      raise 'argh'
    end
end
562

563 564
class LoadAllFixturesTest < ActiveRecord::TestCase
  self.fixture_path = FIXTURES_ROOT + "/all"
565 566 567 568 569 570
  fixtures :all

  def test_all_there
    assert_equal %w(developers people tasks), fixture_table_names.sort
  end
end
571

572
class FasterFixturesTest < ActiveRecord::TestCase
573
  fixtures :categories, :authors
574

575
  def load_extra_fixture(name)
576
    fixture = create_fixtures(name).first
J
Jason Noble 已提交
577
    assert fixture.is_a?(ActiveRecord::Fixtures)
578 579
    @loaded_fixtures[fixture.table_name] = fixture
  end
580

581
  def test_cache
J
Jason Noble 已提交
582 583
    assert ActiveRecord::Fixtures.fixture_is_cached?(ActiveRecord::Base.connection, 'categories')
    assert ActiveRecord::Fixtures.fixture_is_cached?(ActiveRecord::Base.connection, 'authors')
584

585 586 587 588
    assert_no_queries do
      create_fixtures('categories')
      create_fixtures('authors')
    end
589

590
    load_extra_fixture('posts')
J
Jason Noble 已提交
591
    assert ActiveRecord::Fixtures.fixture_is_cached?(ActiveRecord::Base.connection, 'posts')
592 593 594 595
    self.class.setup_fixture_accessors('posts')
    assert_equal 'Welcome to the weblog', posts(:welcome).title
  end
end
596

597
class FoxyFixturesTest < ActiveRecord::TestCase
598
  fixtures :parrots, :parrots_pirates, :pirates, :treasures, :mateys, :ships, :computers, :developers, :"admin/accounts", :"admin/users"
599 600

  def test_identifies_strings
J
Jason Noble 已提交
601 602
    assert_equal(ActiveRecord::Fixtures.identify("foo"), ActiveRecord::Fixtures.identify("foo"))
    assert_not_equal(ActiveRecord::Fixtures.identify("foo"), ActiveRecord::Fixtures.identify("FOO"))
603 604 605
  end

  def test_identifies_symbols
J
Jason Noble 已提交
606
    assert_equal(ActiveRecord::Fixtures.identify(:foo), ActiveRecord::Fixtures.identify(:foo))
607 608
  end

609
  def test_identifies_consistently
J
Jason Noble 已提交
610 611
    assert_equal 207281424, ActiveRecord::Fixtures.identify(:ruby)
    assert_equal 1066363776, ActiveRecord::Fixtures.identify(:sapphire_2)
612 613
  end

614 615 616 617 618 619 620 621
  TIMESTAMP_COLUMNS = %w(created_at created_on updated_at updated_on)

  def test_populates_timestamp_columns
    TIMESTAMP_COLUMNS.each do |property|
      assert_not_nil(parrots(:george).send(property), "should set #{property}")
    end
  end

622 623 624 625 626 627
  def test_does_not_populate_timestamp_columns_if_model_has_set_record_timestamps_to_false
    TIMESTAMP_COLUMNS.each do |property|
      assert_nil(ships(:black_pearl).send(property), "should not set #{property}")
    end
  end

628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
  def test_populates_all_columns_with_the_same_time
    last = nil

    TIMESTAMP_COLUMNS.each do |property|
      current = parrots(:george).send(property)
      last ||= current

      assert_equal(last, current)
      last = current
    end
  end

  def test_only_populates_columns_that_exist
    assert_not_nil(pirates(:blackbeard).created_on)
    assert_not_nil(pirates(:blackbeard).updated_on)
  end

  def test_preserves_existing_fixture_data
646 647
    assert_equal(2.weeks.ago.to_date, pirates(:redbeard).created_on.to_date)
    assert_equal(2.weeks.ago.to_date, pirates(:redbeard).updated_on.to_date)
648 649 650 651 652 653 654
  end

  def test_generates_unique_ids
    assert_not_nil(parrots(:george).id)
    assert_not_equal(parrots(:george).id, parrots(:louis).id)
  end

655 656 657 658 659 660 661 662
  def test_automatically_sets_primary_key
    assert_not_nil(ships(:black_pearl))
  end

  def test_preserves_existing_primary_key
    assert_equal(2, ships(:interceptor).id)
  end

663 664 665 666
  def test_resolves_belongs_to_symbols
    assert_equal(parrots(:george), pirates(:blackbeard).parrot)
  end

667 668 669 670
  def test_ignores_belongs_to_symbols_if_association_and_foreign_key_are_named_the_same
    assert_equal(developers(:david), computers(:workstation).developer)
  end

671 672 673 674 675 676 677 678 679 680 681 682
  def test_supports_join_tables
    assert(pirates(:blackbeard).parrots.include?(parrots(:george)))
    assert(pirates(:blackbeard).parrots.include?(parrots(:louis)))
    assert(parrots(:george).pirates.include?(pirates(:blackbeard)))
  end

  def test_supports_inline_habtm
    assert(parrots(:george).treasures.include?(treasures(:diamond)))
    assert(parrots(:george).treasures.include?(treasures(:sapphire)))
    assert(!parrots(:george).treasures.include?(treasures(:ruby)))
  end

683 684 685 686 687 688
  def test_supports_inline_habtm_with_specified_id
    assert(parrots(:polly).treasures.include?(treasures(:ruby)))
    assert(parrots(:polly).treasures.include?(treasures(:sapphire)))
    assert(!parrots(:polly).treasures.include?(treasures(:diamond)))
  end

689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
  def test_supports_yaml_arrays
    assert(parrots(:louis).treasures.include?(treasures(:diamond)))
    assert(parrots(:louis).treasures.include?(treasures(:sapphire)))
  end

  def test_strips_DEFAULTS_key
    assert_raise(StandardError) { parrots(:DEFAULTS) }

    # this lets us do YAML defaults and not have an extra fixture entry
    %w(sapphire ruby).each { |t| assert(parrots(:davey).treasures.include?(treasures(t))) }
  end

  def test_supports_label_interpolation
    assert_equal("frederick", parrots(:frederick).name)
  end
704 705 706 707 708

  def test_supports_polymorphic_belongs_to
    assert_equal(pirates(:redbeard), treasures(:sapphire).looter)
    assert_equal(parrots(:louis), treasures(:ruby).looter)
  end
709

710 711 712 713 714
  def test_only_generates_a_pk_if_necessary
    m = Matey.find(:first)
    m.pirate = pirates(:blackbeard)
    m.target = pirates(:redbeard)
  end
715 716 717 718 719

  def test_supports_sti
    assert_kind_of DeadParrot, parrots(:polly)
    assert_equal pirates(:blackbeard), parrots(:polly).killer
  end
720 721 722 723 724

  def test_namespaced_models
    assert admin_accounts(:signals37).users.include?(admin_users(:david))
    assert_equal 2, admin_accounts(:signals37).users.size
  end
725
end
726

727
class ActiveSupportSubclassWithFixturesTest < ActiveRecord::TestCase
728 729 730 731 732 733 734
  fixtures :parrots

  # This seemingly useless assertion catches a bug that caused the fixtures
  # setup code call nil[]
  def test_foo
    assert_equal parrots(:louis), Parrot.find_by_name("King Louis")
  end
735
end
736 737

class FixtureLoadingTest < ActiveRecord::TestCase
738 739 740 741 742
  def test_logs_message_for_failed_dependency_load
    ActiveRecord::TestCase.expects(:require_dependency).with(:does_not_exist).raises(LoadError)
    ActiveRecord::Base.logger.expects(:warn)
    ActiveRecord::TestCase.try_to_load_dependency(:does_not_exist)
  end
743

744 745 746 747
  def test_does_not_logs_message_for_successful_dependency_load
    ActiveRecord::TestCase.expects(:require_dependency).with(:works_out_fine)
    ActiveRecord::Base.logger.expects(:warn).never
    ActiveRecord::TestCase.try_to_load_dependency(:works_out_fine)
748 749
  end
end
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774

class CustomNameForFixtureOrModelTest < ActiveRecord::TestCase
  ActiveRecord::Fixtures.reset_cache

  set_fixture_class :randomly_named_a9         =>
                        ClassNameThatDoesNotFollowCONVENTIONS,
                    :'admin/randomly_named_a9' =>
                        Admin::ClassNameThatDoesNotFollowCONVENTIONS,
                    'admin/randomly_named_b0'  =>
                        Admin::ClassNameThatDoesNotFollowCONVENTIONS

  fixtures :randomly_named_a9, 'admin/randomly_named_a9',
           :'admin/randomly_named_b0'

  def test_named_accessor_for_randomly_named_fixture_and_class
    assert_kind_of ClassNameThatDoesNotFollowCONVENTIONS,
                   randomly_named_a9(:first_instance)
  end

  def test_named_accessor_for_randomly_named_namespaced_fixture_and_class
    assert_kind_of Admin::ClassNameThatDoesNotFollowCONVENTIONS,
                   admin_randomly_named_a9(:first_instance)
    assert_kind_of Admin::ClassNameThatDoesNotFollowCONVENTIONS,
                   admin_randomly_named_b0(:second_instance)
  end
775 776 777 778 779

  def test_table_name_is_defined_in_the_model
    assert_equal :randomly_named_table, ActiveRecord::Fixtures::all_loaded_fixtures["admin/randomly_named_a9"].table_name
    assert_equal :randomly_named_table, Admin::ClassNameThatDoesNotFollowCONVENTIONS.table_name
  end
780
end