ruby-on-rails - 链接 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
. 这行得通,但我觉得必须有更好的方法。想法?
解决方案
也许你想要这个:
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)
推荐阅读
- python - 在后端使用快速 api 和 mongo;为获取请求获取“value_error.missing”
- r - 如何在一个循环中获取九 (9) 个子系列的准确度度量
- mysql - 如何使用 AG-Grid valueSetter 使用 NULL 值更新 MySQL 记录?
- javascript - 使用屏蔽 url nodeJS 重定向到新选项卡
- image-processing - 处理错误 ArrayIndexOutOfBoundsException: 32
- c++ - 为什么使用调试进行构建但发布没有?
- python - 什么可能导致 Flask 服务器在只服务一个请求后变得无响应?
- reactjs - 使用多个数据数组作为状态
- scala - 动态选择列
- apache-spark - 通过 pyspark 以 RCFile 格式保存数据的问题