How can I build/create a many-to-many association in factory_girl?

我们两清 提交于 2019-12-03 20:34:48

Ok, I think I understand what you're asking now. Something like this should work (untested, but I've done something similar in another project):

Factory.define :person do |f|
  f.first_name 'John'
  f.last_name 'Doe'
end

Factory.define :email do |f|
end

# This is optional for isolating association testing; if you want this 
# everywhere, add the +after_build+ block to the :person factory definition
Factory.define :person_with_email, :parent => :person do |f|
  f.after_build do |p|
    p.emails << Factory(:email, :email => "#{p.first_name}.#{p.last_name}@gmail.com")
    # OR
    # Factory(:email, :person => p, :email => "#{p.first_name}.#{p.last_name}@gmail.com")
  end
end

As noted, using a third, separate factory is optional. In my case I didn't always want to generate the association for every test, so I made a separate factory that I only used in a few specific tests.

Use a callback (see FG docs for more info). Callbacks get passed the current model being built.

Factory.define :person do |p|
  p.first_name { Factory.next(:first_name) }
  p.last_name { Factory.next(:last_name) }
  p.after_build { |m| p.email_addresses << "#{m.first_name}.#{m.last_name}@test.com" }
end

I think that works.

You could also save yourself some work by looking into using the Faker gem which creates realistic first and last names and e-mail addresses for you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!