【问题标题】:factory girl and nested_attributes in rails 3工厂女孩和 Rails 3 中的嵌套属性
【发布时间】:2011-04-20 15:35:49
【问题描述】:

我有 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

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,但似乎找不到我要找的东西。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 rspec factory-bot rspec-rails


    【解决方案1】:

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

    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 的集成。不过,如果您有兴趣,欢迎提供任何意见。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多