I have a problem where after_build don't seem to trigger after after the actual build. As the example below illustrates, the after_build shouldn't build a second tail when called through Factory.build :tail, since there is already a tail.
Anyone who knows how to solve this? Or how to patch Factory Girl to behave as expected.
Disregard the fact that cat's generally don't have multiple tails etc. :)
Modelsclass Cat
include Mongoid::Document
embeds_many :tails
end
class Tail
include Mongoid::Document
embedded_in :cat
end
Factories
Factory.define开发者_如何学编程 :cat do |a|
a.after_build do |cat|
Factory.build :tail, :cat => cat if cat.tails.empty?
end
end
Factory.define :tail do |a|
a.association :cat, :factory => :cat
end
Problem
>> tail = Factory.build :tail
=> #<Tail _id: 4d839b5930efd431c7000008, >
>> tail.cat.tails.length
=> 2 # this should be 1
>> cat = Factory.build :cat
=> #<Cat _id: 4d839b6c30efd431c700000b, >
>> cat.tails.length
=> 1
I would refrain from defining a default factory of a tail which creates a cat and embeds the tail.
Factory.define :cat do |a|
a.after_build do |cat|
cat.tails << Factory.build(:tail) if cat.tails.empty?
end
end
Factory.define :tail do |a|
end
Factory.define :cat_tail, :parent => :tail do |a|
a.association :cat, :factory => :cat
end
This is what I ended up using. I followed Marcels suggestion of using a separate factory, though after_build still caused the same problem (two tails instead of the expected one), so it had to go too. if cat.tails.empty? don't work as expected for some reason.
Factory.define :cat_tail, :parent => :tail do |a|
a.association :cat, :factory => :cat
end
Factory.define :tail do |a|
end
Factory.define :cat do |a|
end
精彩评论