How to write test about validates_associated

Here is my model:

class Account < ActiveRecord::Base

has_many :users, :dependent => :destroy
has_many :bus
belongs_to :currency
has_many :mylogs, :dependent => :destroy
has_many :batchuserdefines, :dependent => :destroy
has_many :materialuserdefines, :dependent => :destroy
has_many :materials
has_many :inventories
has_many :batchs
has_many :courses
has_many :projects
has_many :initstocks,:dependent => :destroy
has_many :vouchertypes, :dependent => :destroy
has_one :coursecodeformat, :dependent => :destroy

validates_uniqueness_of :name_native
validates_uniqueness_of :code
validates_presence_of :code
validates_presence_of :name_native
validates_presence_of :email
validates_presence_of :phone
validates_associated :currency
validates_associated :coursecodeformat
validates_associated :vouchertypes
end

and here is my test:

require File.dirname(FILE) + ‘/…/test_helper’

class AccountTest < Test::Unit::TestCase

def test_validate_present
account = Account.new
assert !account.valid?
assert account.errors.invalid?(:name_native)
assert !account.errors.invalid?(:code)
assert account.errors.invalid?(:email)
assert account.errors.invalid?(:phone)
assert account.errors.invalid?(:currency)
assert account.errors.invalid?(:coursecodeformat)
assert account.errors.invalid?(:vouchertypes)
end
end

and the resualt:
test_validate_present(AccountTest) [test/unit/account_test.rb:12]:
(false) is not true.

It looks the test failed at assert account.errors.invalid?(:currency)

I feel puzzle. The model and the test looks simple,why failed

Michael G. wrote:

Here is my model:

class Account < ActiveRecord::Base
belongs_to :currency
validates_associated :currency
validates_associated :coursecodeformat
validates_associated :vouchertypes
end

and here is my test:

require File.dirname(FILE) + ‘/…/test_helper’

class AccountTest < Test::Unit::TestCase

def test_validate_present
account = Account.new
assert account.errors.invalid?(:currency)
end
end

and the resualt:
test_validate_present(AccountTest) [test/unit/account_test.rb:12]:
(false) is not true.

It looks the test failed at assert account.errors.invalid?(:currency)

I feel puzzle. The model and the test looks simple,why failed

I think you mis-understood the docs

http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M001055

validates_associated - “Validates whether the associated object or
objects are all valid themselves”

ie. it doesn’t validate that there is a currency,
it just says something like;

def account.errors.invalid?(:currency)
if account.currency
account.currency.invalid?
else
return false
end
end

so at the moment the test would only pass if you did

account = Account.new
account.build_currency(:something => :invalid)

think maybe “validates_presence_of :currency” will work for you.

Ok,it work,thanks