问题
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.
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/14162344/rails-3-factory-girl-many-to-many-relationships