4

私は2つのモデルを持っており、1つはもう一方の属性を受け入れ、Factorygirlを使用して両方のデータをセットアップする賢い方法を見つけようとしています。

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

Booking_spec

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を見回しましたが、探しているものが見つからなかったようです。

4

1 に答える 1

8

私があなたを正しく理解しているなら、あなたはこれをしたいのですが、より簡潔な構文で:

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プラグインでは、次のようになります。

models { booking - booking_item(:people => 3) }
booking.should be_valid

残念ながら、factory_girlとの統​​合はまだ実装していません。興味があればどんな入力でも大歓迎ですが。

于 2011-04-20T16:23:40.993 に答える