【问题标题】:FactoryGirl attributes_for with associationsFactoryGirl attributes_for 与关联
【发布时间】:2014-03-04 11:31:03
【问题描述】:
有以下工厂:
factory :car do
name 'Some car'
engine_value 1.6
color '#ff0000'
car_type
engine_type
transmission
drive_type
material
end
如您所见,有很多关联的对象。但是代码
attributes_for(:car)
仅生成 :name=>"Some car", :engine_value=>1.6, :color=>"#ff0000"} 哈希。我需要得到一个包含所有属性的哈希。我该怎么做?谢谢。
【问题讨论】:
标签:
ruby-on-rails
rspec
factory-bot
【解决方案1】:
我遇到了同样的问题,我用过类似的东西
build(:car).attributes
不确定这是否是最好的方法,但它对我有用
希望对你有帮助
【解决方案2】:
您可能希望省略 id、created_at 和 updated_at 属性。
FactoryGirl.build(:car).attributes.except('id', 'created_at', 'updated_at')
如果您需要键是符号(如attributes_for 生成的键):
FactoryGirl.build(:car).attributes.except('id', 'created_at', 'updated_at').symbolize_keys
限制:
- 它不会为 HMT 和 HABTM 关联生成属性(因为这些关联存储在连接表中,而不是实际属性中)。
- 工厂中的关联策略必须为
create,如association :user, strategy: :create。如果您不明智地使用此策略,可能会使您的工厂变得非常缓慢。