Factory Girl的额外参数

pup*_*eno 22 ruby ruby-on-rails factory-bot

我需要将额外的参数传递给工厂女孩以用于回调.像这样的东西(但实际上更复杂):

Factory.define :blog do |blog|
  blog.name "Blah"

  blog.after_create do |blog|
    blog.posts += sample_posts
    blog.save!
  end
end
Run Code Online (Sandbox Code Playgroud)

然后使用以下内容创建它:

Factory.create(:blog, :sample_posts => [post1, post2])
Run Code Online (Sandbox Code Playgroud)

有什么想法怎么做?

win*_*ons 32

由于瞬态属性,现在可以在没有任何"黑客"的情况下实现(参见问题#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"
Run Code Online (Sandbox Code Playgroud)

对于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"
Run Code Online (Sandbox Code Playgroud)

  • 这里有用的文档集,包括如何从after_create或其他块访问transient属性:https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md (3认同)