views:

61

answers:

1

hey,

i have a simple associations:

class Account < ActiveRecord::Base
  has_many :users

  accepts_nested_attributes_for :users
  validates_presence_of :users
end

and

class User < ActiveRecord::Base
  belongs_to :account
end

i just want to run a simple test:

describe 'a new', Account do
  it 'should be valid' do
    Factory.build(:account).should be_valid
  end
end

with the factories:

Factory.define :account do |a|
  a.name                 { Faker::Company.name }
end

Factory.define :user do |u|
  u.association           :account
  u.email                 { Faker::Internet.email }
end

but i always run into this error:

'a new Account should be valid' FAILED
Expected #<Account id: nil, name: "Baumbach, Gerlach and Murray" > to be valid, but it was not
Errors: Users has to be present

well, i setup the correct associations, but it doesn't work...

thx for your help.

+1  A: 

validates_presence_of :users in your Account model is responsible for the failing test. You need at least one user in your Account, so it can be created.

I'm not sure what you really want to do, so I'm giving you to ways to solve this Problem. The first option is to change your factory:

Factory.define :account do |a|
  a.name                 { Faker::Company.name }
  a.users                {|u| [u.association(:user)]}
end

Factory.define :user do |u|
  u.email                 { Faker::Internet.email }
end

Another way is to check the presence of the association on the belongs to side. So you need to change your models like this:

class Account < ActiveRecord::Base
  has_many :users

  accepts_nested_attributes_for :users
end


class User < ActiveRecord::Base
  belongs_to :account
  validates_presence_of :account
end
jigfox
your second tipp works. i thought rails does not validates the user unless you have the "validates_presence_of :user", but it seems that it does, unless i explicit define: accepts_nested_attributes_for :users, :reject_if => :all_blankthx, for the quick response.
kalle
rails doesn't validate the user if you have not `validates_presence_of :user`. But you had it set so it validates the presence of the user. Your code said that you want some users prestent in your account model. BUt you don't give the accout in the factory any users, so it must fail!
jigfox