首页 > 解决方案 > 链接 FactoryBot 关联

问题描述

考虑以下工厂:

factory :position do
  association :underlying
end

factory :short_put, class: 'Trade' do
  position { association :position }
  strike { 115 }
end

我想针对与 Trade 的 short_put 实例关联的 Position 实例运行测试。如果我实例化以下变量:

@position = create(:position)
@short_put = create(:short_put)

然后启动两个单独的位置并将其保存到数据库中。只有@short_put与职位相关联。

为了测试与 :short_put 关联的位置,我使用@short_put.position. 这行得通,但我觉得必须有更好的方法。想法?

标签: ruby-on-railsrubyfactory-bot

解决方案


也许你想要这个:

factory :position do
  association :underlying

  trait :with_short_put do
    after :build do |position|
      position.short_puts << build(:short_put, position: position)
      #position.short_put = build(:short_put, position: position) #when has one
    end
  end
end

使用后

create(:position, :with_short_put)

推荐阅读