使用FactoryGirl,如何将accepts_nested_attributes_for 子属性插入到我正在创建的对象中?

发布于 2024-11-23 19:12:16 字数 305 浏览 1 评论 0原文

factory :payment_object do
  company_id 1
  user_id 1
  delivery_date (Date.today + 1)
  payment_terms 'CBD'
  vendor 'Apple'
  currency 'USD'

  # item
    # name "Macbook"
    # quantity 1
    # price 1000
  # item
    # name "Magic Mouse"
    # quantity 1
    # price 65   
end
factory :payment_object do
  company_id 1
  user_id 1
  delivery_date (Date.today + 1)
  payment_terms 'CBD'
  vendor 'Apple'
  currency 'USD'

  # item
    # name "Macbook"
    # quantity 1
    # price 1000
  # item
    # name "Magic Mouse"
    # quantity 1
    # price 65   
end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

白馒头 2024-11-30 19:12:16

这是一种可以在您的规格内完成此操作的方法。

before(:each) do
  @payment_object = FactoryGirl.build(:payment_object)
  5.times do 
    @payment_object.items << FactoryGirl.build(:item)
  end
  @payment_object.save!
end

Here's a way you can do it inside your specs.

before(:each) do
  @payment_object = FactoryGirl.build(:payment_object)
  5.times do 
    @payment_object.items << FactoryGirl.build(:item)
  end
  @payment_object.save!
end
指尖上得阳光 2024-11-30 19:12:16

这是不直观的,但 Factory_girl 文档说明了当您搜索“has_many”时如何:
https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md基本上

,首先,创建另一个工厂:

FactoryGirl.define do
  factory :item do
    name "Macbook"
    quantity 1
    price 1000
    payment_object
  end
end

然后在代码中使用它,如下所示:

FactoryGirl.define do
  factory :payment_object do
    company_id 1
    user_id 1
    delivery_date (Date.today + 1)
    payment_terms 'CBD'
    vendor 'Apple'
    currency 'USD'

    # This is how you reference the list with your items
    ignore do
      items_count 5  # the number items that should be in the list
    end
    after(:create) do |payment_object, evaluator|
        FactoryGirl.create_list(:item, evaluator.items_count, payment_object: payment_object)
    end


  end

It's unintuitive, but the factory_girl docs states how, when you search for 'has_many':
https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md

Basically, first, make another factory:

FactoryGirl.define do
  factory :item do
    name "Macbook"
    quantity 1
    price 1000
    payment_object
  end
end

Then use that within your code, like this:

FactoryGirl.define do
  factory :payment_object do
    company_id 1
    user_id 1
    delivery_date (Date.today + 1)
    payment_terms 'CBD'
    vendor 'Apple'
    currency 'USD'

    # This is how you reference the list with your items
    ignore do
      items_count 5  # the number items that should be in the list
    end
    after(:create) do |payment_object, evaluator|
        FactoryGirl.create_list(:item, evaluator.items_count, payment_object: payment_object)
    end


  end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文