我需要将额外的参数传递给工厂女孩以用于回调。像这样的东西(但实际上更复杂):
Factory.define :blog do |blog|
blog.name "Blah"
blog.after_create do |blog|
blog.posts += sample_posts
blog.save!
end
end
然后使用以下内容创建它:
Factory.create(:blog, :sample_posts => [post1, post2])
任何想法怎么做?
答案 0 :(得分:32)
由于瞬态属性(see comment on issue #49)
,现在可以在没有任何“黑客”的情况下实现示例:
FactoryGirl.define do
factory :user do
transient do
bar_extension false
end
name {"foo #{' bar' if bar_extension}"}
end
end
# Factory(:user).name = "foo"
# Factory(:user, :bar_extension => true).name = "foo bar"
对于Factory Girl版本< 5.0:
FactoryGirl.define do
factory :user do
ignore do
bar_extension false
end
name {"foo #{' bar' if bar_extension}"}
end
end
# Factory(:user).name = "foo"
# Factory(:user, :bar_extension => true).name = "foo bar"
答案 1 :(得分:2)
一个选项是为after_create
钩子检查的额外帖子创建一个虚拟访问器:
class Blog
has_many :posts
attr_accessible :name, :title, ... # DB columns
attr_accessor :sample_posts # virtual column
end
Factory.define :blog do |blog|
blog.name 'Blah'
blog.after_create do |b|
b.posts += b.sample_posts
b.save!
end
end
Factory(:blog, :sample_posts => [post1, post2])
答案 2 :(得分:2)
显然,如果没有需要修改模型本身的变通方法,目前这是不可能的。此错误报告在:http://github.com/thoughtbot/factory_girl/issues#issue/49
答案 3 :(得分:1)
另一种选择是使用build
代替create
并将:autosave
添加到集合中:
class Blog
has_many :posts, :autosave => true
end
Factory.define :blog do |blog|
blog.name 'Blah'
blog.posts { |_| [Factory.build(:post)] }
end
Factory(:blog, :posts => [post1, post2])
#or
Factory.build(:blog, :posts => [unsavedPost1, unsavedPost2])
答案 4 :(得分:1)
如果你打开factorygirl文件中的类,我建议你这样做
require "user"
class User
attr :post_count
end
这样你就可以打开课程,而不是覆盖它