简体   繁体   中英

factory girl: association problem testing model which has validates_presence_of accepts_nested_attributes_for

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.

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 two 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM