小编mat*_*ray的帖子

具有嵌套关联的FactoryGirl构建策略

当我有一个与第二个模型有关联的模型的工厂时,是否有可能保留构建策略,第二个模型本身与第三个模型有关联?

在下面的示例中,帖子与用户关联,用户与城市关联.即使:strategy => :build是用于所有关联,post.userpost.user.city最终得到保存到数据库中.为了快速测试套件的利益,我可以防止这些数据库写入发生吗?

Factory.define do 
  factory :user do
    name "A User"
    association :city, :strategy => :build
  end

  factory :city do
    name "A City"
  end

  factory :post do
    title "A Post"
    body  "Some text here"
    association :user, :strategy => :build
  end
end

post = FactoryGirl.build(:post)

post.new_record?           # True
post.user.new_record?      # False
post.user.city.new_record? # False
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails factory-bot

6
推荐指数
1
解决办法
1250
查看次数

标签 统计

factory-bot ×1

ruby-on-rails ×1