Factory Girl - has many associations

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


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"

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

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


describe GroupsController do
  include Devise::TestHelpers

  before (:each) do
    @user1 = Factory.create(:user)
    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)


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


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), 

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.