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

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


Need Your Help

Automatically scale x-axis by date range within a factor using xyplot()

r date pdf-generation axis lattice

I've been trying to write out an R script that will plot the date-temp series for a set of locations that are identified by a Deployment_ID.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.