has_one_associations_test.rb 15.8 KB
Newer Older
1
require "cases/helper"
2 3 4
require 'models/developer'
require 'models/project'
require 'models/company'
5 6
require 'models/ship'
require 'models/pirate'
7
require 'models/car'
8
require 'models/bulb'
9 10
require 'models/author'
require 'models/post'
11 12

class HasOneAssociationsTest < ActiveRecord::TestCase
13
  self.use_transactional_fixtures = false unless supports_savepoints?
14
  fixtures :accounts, :companies, :developers, :projects, :developers_projects, :ships, :pirates
15 16 17 18 19 20 21 22 23

  def setup
    Account.destroyed_account_ids.clear
  end

  def test_has_one
    assert_equal companies(:first_firm).account, Account.find(1)
    assert_equal Account.find(1).credit_limit, companies(:first_firm).account.credit_limit
  end
24

25 26 27 28 29
  def test_has_one_cache_nils
    firm = companies(:another_firm)
    assert_queries(1) { assert_nil firm.account }
    assert_queries(0) { assert_nil firm.account }

30
    firms = Firm.all.merge!(:includes => :account).to_a
31 32 33
    assert_queries(0) { firms.each(&:account) }
  end

34 35
  def test_with_select
    assert_equal Firm.find(1).account_with_select.attributes.size, 2
36
    assert_equal Firm.all.merge!(:includes => :account_with_select).find(1).account_with_select.attributes.size, 2
37 38
  end

39 40
  def test_finding_using_primary_key
    firm = companies(:first_firm)
R
robertomiranda 已提交
41
    assert_equal Account.find_by(firm_id: firm.id), firm.account
42 43 44
    firm.firm_id = companies(:rails_core).id
    assert_equal accounts(:rails_core_account), firm.account_using_primary_key
  end
45 46 47 48

  def test_update_with_foreign_and_primary_keys
    firm = companies(:first_firm)
    account = firm.account_using_foreign_and_primary_keys
R
robertomiranda 已提交
49
    assert_equal Account.find_by(firm_name: firm.name), account
50 51 52 53
    firm.save
    firm.reload
    assert_equal account, firm.account_using_foreign_and_primary_keys
  end
54

55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
  def test_can_marshal_has_one_association_with_nil_target
    firm = Firm.new
    assert_nothing_raised do
      assert_equal firm.attributes, Marshal.load(Marshal.dump(firm)).attributes
    end

    firm.account
    assert_nothing_raised do
      assert_equal firm.attributes, Marshal.load(Marshal.dump(firm)).attributes
    end
  end

  def test_proxy_assignment
    company = companies(:first_firm)
    assert_nothing_raised { company.account = company.account }
  end

  def test_type_mismatch
73 74
    assert_raise(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).account = 1 }
    assert_raise(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).account = Project.find(1) }
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
  end

  def test_natural_assignment
    apple = Firm.create("name" => "Apple")
    citibank = Account.create("credit_limit" => 10)
    apple.account = citibank
    assert_equal apple.id, citibank.firm_id
  end

  def test_natural_assignment_to_nil
    old_account_id = companies(:first_firm).account.id
    companies(:first_firm).account = nil
    companies(:first_firm).save
    assert_nil companies(:first_firm).account
    # account is dependent, therefore is destroyed when reference to owner is lost
90
    assert_raise(ActiveRecord::RecordNotFound) { Account.find(old_account_id) }
91 92
  end

93 94 95
  def test_nullification_on_association_change
    firm = companies(:rails_core)
    old_account_id = firm.account.id
96
    firm.account = Account.new(:credit_limit => 5)
97 98 99 100
    # account is dependent with nullify, therefore its firm_id should be nil
    assert_nil Account.find(old_account_id).firm_id
  end

101 102 103 104 105 106 107 108 109
  def test_natural_assignment_to_nil_after_destroy
    firm = companies(:rails_core)
    old_account_id = firm.account.id
    firm.account.destroy
    firm.account = nil
    assert_nil companies(:rails_core).account
    assert_raise(ActiveRecord::RecordNotFound) { Account.find(old_account_id) }
  end

110
  def test_association_change_calls_delete
111
    companies(:first_firm).deletable_account = Account.new(:credit_limit => 5)
112 113 114 115
    assert_equal [], Account.destroyed_account_ids[companies(:first_firm).id]
  end

  def test_association_change_calls_destroy
116
    companies(:first_firm).account = Account.new(:credit_limit => 5)
117 118 119
    assert_equal [companies(:first_firm).id], Account.destroyed_account_ids[companies(:first_firm).id]
  end

120 121 122 123 124 125 126 127 128 129
  def test_natural_assignment_to_already_associated_record
    company = companies(:first_firm)
    account = accounts(:signals37)
    assert_equal company.account, account
    company.account = account
    company.reload
    account.reload
    assert_equal company.account, account
  end

130 131 132 133
  def test_dependence
    num_accounts = Account.count

    firm = Firm.find(1)
134
    assert_not_nil firm.account
135 136 137 138 139 140 141 142 143 144 145 146
    account_id = firm.account.id
    assert_equal [], Account.destroyed_account_ids[firm.id]

    firm.destroy
    assert_equal num_accounts - 1, Account.count
    assert_equal [account_id], Account.destroyed_account_ids[firm.id]
  end

  def test_exclusive_dependence
    num_accounts = Account.count

    firm = ExclusivelyDependentFirm.find(9)
147
    assert_not_nil firm.account
148 149 150 151 152 153 154 155 156 157 158 159 160
    assert_equal [], Account.destroyed_account_ids[firm.id]

    firm.destroy
    assert_equal num_accounts - 1, Account.count
    assert_equal [], Account.destroyed_account_ids[firm.id]
  end

  def test_dependence_with_nil_associate
    firm = DependentFirm.new(:name => 'nullify')
    firm.save!
    assert_nothing_raised { firm.destroy }
  end

161
  def test_restrict
162
    firm = RestrictedFirm.create!(:name => 'restrict')
A
Aaron Patterson 已提交
163
    firm.create_account(:credit_limit => 10)
164

165
    assert_not_nil firm.account
166

167
    assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
168 169 170 171
    assert RestrictedFirm.exists?(:name => 'restrict')
    assert firm.account.present?
  end

172 173 174 175
  def test_restrict_is_deprecated
    klass = Class.new(ActiveRecord::Base)
    assert_deprecated { klass.has_one :post, dependent: :restrict }
  end
176

177 178
  def test_restrict_with_exception
    firm = RestrictedWithExceptionFirm.create!(:name => 'restrict')
179 180 181 182
    firm.create_account(:credit_limit => 10)

    assert_not_nil firm.account

183 184
    assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
    assert RestrictedWithExceptionFirm.exists?(:name => 'restrict')
185
    assert firm.account.present?
186 187
  end

188 189
  def test_restrict_with_error
    firm = RestrictedWithErrorFirm.create!(:name => 'restrict')
190 191 192 193 194 195 196
    firm.create_account(:credit_limit => 10)

    assert_not_nil firm.account

    firm.destroy

    assert !firm.errors.empty?
197 198
    assert_equal "Cannot delete record because a dependent account exists", firm.errors[:base].first
    assert RestrictedWithErrorFirm.exists?(:name => 'restrict')
199 200 201
    assert firm.account.present?
  end

202
  def test_successful_build_association
203 204 205 206 207 208 209 210
    firm = Firm.new("name" => "GlobalMegaCorp")
    firm.save

    account = firm.build_account("credit_limit" => 1000)
    assert account.save
    assert_equal account, firm.account
  end

211 212 213 214 215 216
  def test_build_association_dont_create_transaction
    assert_no_queries {
      Firm.new.build_account
    }
  end

217 218 219
  def test_building_the_associated_object_with_implicit_sti_base_class
    firm = DependentFirm.new
    company = firm.build_company
220
    assert_kind_of Company, company, "Expected #{company.class} to be a Company"
221 222 223 224 225
  end

  def test_building_the_associated_object_with_explicit_sti_base_class
    firm = DependentFirm.new
    company = firm.build_company(:type => "Company")
226
    assert_kind_of Company, company, "Expected #{company.class} to be a Company"
227 228 229 230 231
  end

  def test_building_the_associated_object_with_sti_subclass
    firm = DependentFirm.new
    company = firm.build_company(:type => "Client")
232
    assert_kind_of Client, company, "Expected #{company.class} to be a Client"
233 234 235 236 237 238 239 240 241 242 243 244
  end

  def test_building_the_associated_object_with_an_invalid_type
    firm = DependentFirm.new
    assert_raise(ActiveRecord::SubclassNotFound) { firm.build_company(:type => "Invalid") }
  end

  def test_building_the_associated_object_with_an_unrelated_type
    firm = DependentFirm.new
    assert_raise(ActiveRecord::SubclassNotFound) { firm.build_company(:type => "Account") }
  end

245 246
  def test_build_and_create_should_not_happen_within_scope
    pirate = pirates(:blackbeard)
J
Jon Leighton 已提交
247
    scoped_count = pirate.association(:foo_bulb).scope.where_values.count
248

249 250
    bulb = pirate.build_foo_bulb
    assert_not_equal scoped_count, bulb.scope_after_initialize.where_values.count
251

252 253
    bulb = pirate.create_foo_bulb
    assert_not_equal scoped_count, bulb.scope_after_initialize.where_values.count
254

255 256
    bulb = pirate.create_foo_bulb!
    assert_not_equal scoped_count, bulb.scope_after_initialize.where_values.count
257 258
  end

259 260 261 262 263 264
  def test_create_association
    firm = Firm.create(:name => "GlobalMegaCorp")
    account = firm.create_account(:credit_limit => 1000)
    assert_equal account, firm.reload.account
  end

265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
  def test_create_association_with_bang
    firm = Firm.create(:name => "GlobalMegaCorp")
    account = firm.create_account!(:credit_limit => 1000)
    assert_equal account, firm.reload.account
  end

  def test_create_association_with_bang_failing
    firm = Firm.create(:name => "GlobalMegaCorp")
    assert_raise ActiveRecord::RecordInvalid do
      firm.create_account!
    end
    account = firm.account
    assert_not_nil account
    account.credit_limit = 5
    account.save
    assert_equal account, firm.reload.account
  end

283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
  def test_build
    firm = Firm.new("name" => "GlobalMegaCorp")
    firm.save

    firm.account = account = Account.new("credit_limit" => 1000)
    assert_equal account, firm.account
    assert account.save
    assert_equal account, firm.account
  end

  def test_create
    firm = Firm.new("name" => "GlobalMegaCorp")
    firm.save
    firm.account = account = Account.create("credit_limit" => 1000)
    assert_equal account, firm.account
  end

  def test_create_before_save
    firm = Firm.new("name" => "GlobalMegaCorp")
    firm.account = account = Account.create("credit_limit" => 1000)
    assert_equal account, firm.account
  end

  def test_dependence_with_missing_association
    Account.destroy_all
    firm = Firm.find(1)
309
    assert_nil firm.account
310 311 312 313 314
    firm.destroy
  end

  def test_dependence_with_missing_association_and_nullify
    Account.destroy_all
315
    firm = DependentFirm.first
316
    assert_nil firm.account
317 318 319
    firm.destroy
  end

320
  def test_finding_with_interpolated_condition
321
    firm = Firm.first
322 323 324 325 326 327
    superior = firm.clients.create(:name => 'SuperiorCo')
    superior.rating = 10
    superior.save
    assert_equal 10, firm.clients_with_interpolated_conditions.first.rating
  end

328 329 330
  def test_assignment_before_child_saved
    firm = Firm.find(1)
    firm.account = a = Account.new("credit_limit" => 1000)
331
    assert a.persisted?
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
    assert_equal a, firm.account
    assert_equal a, firm.account
    assert_equal a, firm.account(true)
  end

  def test_save_still_works_after_accessing_nil_has_one
    jp = Company.new :name => 'Jaded Pixel'
    jp.dummy_account.nil?

    assert_nothing_raised do
      jp.save!
    end
  end

  def test_cant_save_readonly_association
    assert_raise(ActiveRecord::ReadOnlyRecord) { companies(:first_firm).readonly_account.save!  }
    assert companies(:first_firm).readonly_account.readonly?
  end

351
  def test_has_one_proxy_should_not_respond_to_private_methods
352 353
    assert_raise(NoMethodError) { accounts(:signals37).private_method }
    assert_raise(NoMethodError) { companies(:first_firm).account.private_method }
354 355 356 357 358 359 360
  end

  def test_has_one_proxy_should_respond_to_private_methods_via_send
    accounts(:signals37).send(:private_method)
    companies(:first_firm).account.send(:private_method)
  end

361 362 363 364 365 366
  def test_save_of_record_with_loaded_has_one
    @firm = companies(:first_firm)
    assert_not_nil @firm.account

    assert_nothing_raised do
      Firm.find(@firm.id).save!
367
      Firm.all.merge!(:includes => :account).find(@firm.id).save!
368 369 370 371 372 373
    end

    @firm.account.destroy

    assert_nothing_raised do
      Firm.find(@firm.id).save!
374
      Firm.all.merge!(:includes => :account).find(@firm.id).save!
375 376
    end
  end
377 378 379 380 381 382 383 384 385

  def test_build_respects_hash_condition
    account = companies(:first_firm).build_account_limit_500_with_hash_conditions
    assert account.save
    assert_equal 500, account.credit_limit
  end

  def test_create_respects_hash_condition
    account = companies(:first_firm).create_account_limit_500_with_hash_conditions
386
    assert       account.persisted?
387 388
    assert_equal 500, account.credit_limit
  end
389 390 391 392 393

  def test_attributes_are_being_set_when_initialized_from_has_one_association_with_where_clause
    new_account = companies(:first_firm).build_account(:firm_name => 'Account')
    assert_equal new_account.firm_name, "Account"
  end
394 395 396

  def test_creation_failure_without_dependent_option
    pirate = pirates(:blackbeard)
397
    orig_ship = pirate.ship
398 399 400 401 402 403 404 405 406 407 408 409

    assert_equal ships(:black_pearl), orig_ship
    new_ship = pirate.create_ship
    assert_not_equal ships(:black_pearl), new_ship
    assert_equal new_ship, pirate.ship
    assert new_ship.new_record?
    assert_nil orig_ship.pirate_id
    assert !orig_ship.changed? # check it was saved
  end

  def test_creation_failure_with_dependent_option
    pirate = pirates(:blackbeard).becomes(DestructivePirate)
410
    orig_ship = pirate.dependent_ship
411 412 413 414 415

    new_ship = pirate.create_dependent_ship
    assert new_ship.new_record?
    assert orig_ship.destroyed?
  end
416

417 418 419 420 421 422 423 424 425 426 427
  def test_creation_failure_due_to_new_record_should_raise_error
    pirate = pirates(:redbeard)
    new_ship = Ship.new

    assert_raise(ActiveRecord::RecordNotSaved) do
      pirate.ship = new_ship
    end
    assert_nil pirate.ship
    assert_nil new_ship.pirate_id
  end

428 429 430 431 432 433 434 435 436 437 438
  def test_replacement_failure_due_to_existing_record_should_raise_error
    pirate = pirates(:blackbeard)
    pirate.ship.name = nil

    assert !pirate.ship.valid?
    assert_raise(ActiveRecord::RecordNotSaved) do
      pirate.ship = ships(:interceptor)
    end
    assert_equal ships(:black_pearl), pirate.ship
    assert_equal pirate.id, pirate.ship.pirate_id
  end
439 440 441 442 443 444 445 446

  def test_replacement_failure_due_to_new_record_should_raise_error
    pirate = pirates(:blackbeard)
    new_ship = Ship.new

    assert_raise(ActiveRecord::RecordNotSaved) do
      pirate.ship = new_ship
    end
447 448 449 450
    assert_equal ships(:black_pearl), pirate.ship
    assert_equal pirate.id, pirate.ship.pirate_id
    assert_equal pirate.id, ships(:black_pearl).reload.pirate_id
    assert_nil new_ship.pirate_id
451
  end
452

453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
  def test_association_keys_bypass_attribute_protection
    car = Car.create(:name => 'honda')

    bulb = car.build_bulb
    assert_equal car.id, bulb.car_id

    bulb = car.build_bulb :car_id => car.id + 1
    assert_equal car.id, bulb.car_id

    bulb = car.create_bulb
    assert_equal car.id, bulb.car_id

    bulb = car.create_bulb :car_id => car.id + 1
    assert_equal car.id, bulb.car_id
  end

469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
  def test_association_protect_foreign_key
    pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?")

    ship = pirate.build_ship
    assert_equal pirate.id, ship.pirate_id

    ship = pirate.build_ship :pirate_id => pirate.id + 1
    assert_equal pirate.id, ship.pirate_id

    ship = pirate.create_ship
    assert_equal pirate.id, ship.pirate_id

    ship = pirate.create_ship :pirate_id => pirate.id + 1
    assert_equal pirate.id, ship.pirate_id
  end

485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
  def test_build_with_block
    car = Car.create(:name => 'honda')

    bulb = car.build_bulb{ |b| b.color = 'Red' }
    assert_equal 'RED!', bulb.color
  end

  def test_create_with_block
    car = Car.create(:name => 'honda')

    bulb = car.create_bulb{ |b| b.color = 'Red' }
    assert_equal 'RED!', bulb.color
  end

  def test_create_bang_with_block
    car = Car.create(:name => 'honda')

    bulb = car.create_bulb!{ |b| b.color = 'Red' }
    assert_equal 'RED!', bulb.color
  end
505 506 507 508 509 510 511

  def test_association_attributes_are_available_to_after_initialize
    car = Car.create(:name => 'honda')
    bulb = car.create_bulb

    assert_equal car.id, bulb.attributes_after_initialize['car_id']
  end
512

513 514 515 516 517 518 519 520 521 522 523 524
  def test_has_one_transaction
    company = companies(:first_firm)
    account = Account.find(1)

    company.account # force loading
    assert_no_queries { company.account = account }

    company.account = nil
    assert_no_queries { company.account = nil }
    account = Account.find(2)
    assert_queries { company.account = account }
  end
525
end