gpt4 book ai didi

ruby-on-rails - rails 3 中的工厂女孩​​和嵌套属性

转载 作者:行者123 更新时间:2023-12-04 03:34:45 26 4
gpt4 key购买 nike

我有 2 个模型,一个接受另一个模型的属性,我试图找到一种聪明的方法来使用 Factory girl 为两者设置数据。

Class Booking
has_many :booking_items
accepts_nested_attributes_for :booking_items

Class BookingItem
belong_to :booking

我的工厂
Factory.define :booking do |f|
f.bookdate Date.today+15.days
f.association :space
f.nights 2
f.currency "EUR"
f.booking_item_attributes Factory.build(:booking_item) # doesn't work
end

Factory.define :booking_item do |f|
f.association :room
f.bookdate Date.today
f.people 2
f.total_price 20
f.association :booking
end

预订规范
require "spec_helper"

describe Booking do

before(:each) do
@booking = Factory.create(:booking)
end

it "should be valid" do
#needs children to be valid
@booking.should be_valid
end


end

我环顾了 rdocs,但似乎找不到我要找的东西。

最佳答案

如果我理解正确,你想这样做,但使用更简洁的语法:

booking_item = Factory(:booking_item, :people => 4)
booking = Factory(:booking, :booking_item => booking_item)

因为你可以像这样快捷方式:
def with_assocs factory, assocs_hashes = {}, attrs = {}
assoc_models = Hash[ assocs_hash.map { |k, v| [k, Factory(k, v)] } ]
Factory factory, attrs.merge(assoc_models)
end

并像这样使用:
@booking = with_assocs :booking, :booking_item => {:people => 3}
@booking.should be_valid

active_factory plugin使用类似的工厂定义,它看起来像这样:
models { booking - booking_item(:people => 3) }
booking.should be_valid

不幸的是,我还没有实现与 factory_girl 的集成。不过,如果您有兴趣,我们非常欢迎您提供任何意见。

关于ruby-on-rails - rails 3 中的工厂女孩​​和嵌套属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5732950/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com