Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 Factory Girl + Many to Many Relationships

There aren't currently any up to date answers for this using Factory Girl 4.1 (that I could find) - how do you setup a many to many relationship inside of a factory?

For instance I have Students and Classrooms which are in a many to many relationship using a join table, so far I had the following setup:

factory :classroom do
    name "Foo Class"
    ...
end

factory :student do
   name "John Doe"
   ...
end

factory :student_with_classroom, :parent => :student do
    after(:build) {|student| student.classrooms << classroom}
end

However this results in:

NameError:
       undefined local variable or method `classroom' for #<FactoryGirl::SyntaxRunner>

My attempt was guesswork for the most part as I had no luck finding any non-deprecated syntax to accomplish this.

like image 217
Noz Avatar asked Jan 04 '13 17:01

Noz


2 Answers

Actually I managed to find the answer I was looking for buried under a slew of other answers in this SO: How to create has_and_belongs_to_many associations in Factory girl

factory :classroom do
    name "Foo Class"
    ...
end

factory :student do
   name "John Doe"
   ...
end

factory :student_with_classroom, :parent => :student do
    classrooms {[FactoryGirl.create(:classroom)]}
end
like image 61
Noz Avatar answered Sep 30 '22 01:09

Noz


Check out this SO post: How to set up factory in FactoryGirl with has_many association. It will point you to https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md; search for has_many.

like image 38
michael Avatar answered Sep 30 '22 01:09

michael