Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factory Girl - has many associations

I'm using factory girl with rspec, here is what I have:

factories.rb

Factory.define :user do |f|
  f.sequence(:fname) { |n| "fname#{n}" }
  f.sequence(:lname) { |n| "lname#{n}" }
  f.sequence(:email) { |n| "email#{n}@google.com" }
  f.password               "password"
  f.password_confirmation { |u| u.password }
  f.invitation_code        "xxxxxxx"
end

Factory.define :group do |f|
  f.sequence(:name) { |n| "myGroup#{n}" }
  f.sequence(:private_email) { |n| "myGroup#{n}" }
end

Factory.define :permission do |f|
  f.role_id         1
end

groups_controller_spec.rb

describe GroupsController do
  include Devise::TestHelpers

  before (:each) do
    @user1 = Factory.create(:user)
    @user1.confirm!
    sign_in @user1
    @group = Factory.create(:group)
    @group2 = Factory.create(:group)
    @group3 = Factory.create(:group)
    @permission_user_1 = Factory.create(:permission, :user => @user1, :creator_id => @user1.id, :group => @group)
    @permission_user_2 = Factory.create(:permission, :user => @user1, :creator_id => @user1.id, :group => @group2)
    @permission_user_3 = Factory.create(:permission, :user => @user1, :creator_id => @user1.id, :group => @group3)
  end

.......

Problem is the group model has a field for user_id which is not being set by factory. How can I create a users, and then have factory create a group on behalf of that user. Like @user1.group.factory.create(:group)?

Any ideas? Thanks

like image 494
AnApprentice Avatar asked Dec 07 '22 21:12

AnApprentice


1 Answers

Don't do this for all users instead create another factory that inherits from the user factory.

Factory.define :user_with_group, :parent => :user do |u|
  u.groups  { |g| [ g.association(:group), 
                    g.association(:group)
                  ]}
end

you can see lots of example factories at https://github.com/drhenner/ror_ecommerce/tree/master/spec/factories

like image 59
drhenner Avatar answered Dec 28 '22 14:12

drhenner