【问题标题】:FactoryGirl build strategy with nested associationsFactoryGirl 使用嵌套关联构建策略
【发布时间】:2019-01-27 00:31:01
【问题描述】:

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

在下面的示例中,帖子与用户相关联,用户与城市相关联。即使 :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

【问题讨论】:

    标签: ruby-on-rails factory-bot


    【解决方案1】:

    您是否尝试过替代块语法?

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

    【讨论】:

      【解决方案2】:

      看起来 FactoryBot(以前的 FactoryGirl)在 v4.8.0 中添加了 use_parent_strategy 作为配置选项。默认情况下它是关闭的,要打开它,请将以下内容添加到您的spec/rails_helper

      FactoryGirl.use_parent_strategy = true
      

      factory_bot repo 上的相关拉取请求:https://github.com/thoughtbot/factory_bot/pull/961

      【讨论】:

        【解决方案3】:

        正如@messanjah 所说,但是对于旧版本(

        association :user, :strategy => @build_strategy.class
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多