【问题标题】:How to create an object in factory_girl which validates that it has at least one associated object?如何在 factory_girl 中创建一个对象来验证它是否具有至少一个关联对象?
【发布时间】:2014-06-06 11:56:42
【问题描述】:

有如下代码:

  let!(:beauty_salon_service) { create(:beauty_salon_service) }
  let!(:beauty_salon_employee) { build(:beauty_salon_employee, 
                                       business: beauty_salon_service.beauty_salon_category.business) }
  before do
    beauty_salon_employee.beauty_salon_employee_services.build(beauty_salon_service: beauty_salon_service)
    beauty_salon_employee.save!
  end

两个条件:

  1. beauty_salon_service 和 beauty_salon_employee 必须指向 相同的业务(你可以看到它);
  2. beauty_salon_employee 必须没有 空白 has_many 通过关联 beauty_salon_employee_services (验证存在);

我的 FactoryGirl 代码不起作用 - “验证失败:美容院员工服务不能为空”。我该如何解决?提前致谢。

【问题讨论】:

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


    【解决方案1】:

    let! 发生在before 之前,因此创建员工时没有服务(您可能知道这一点)。要解决您当前的问题,您需要在创建员工时提供服务。

    当您在 factory_girl(或 ActiveRecord 中)创建对象时,您可以像这样初始化多对多关系:

    let!(:beauty_salon_employee) do
      build :beauty_salon_employee,
        business: beauty_salon_service.beauty_salon_category.business,
        beauty_salon_employee_services: [beauty_salon_service]
    end
    

    虽然您可能真正想做的是在 BeautySalonFactory 中创建 BeautySalonService。 The factory_girl documentation for associations 给出了如何在回调中填充一对多关联的示例:

    FactoryGirl.define do
    
      # post factory with a `belongs_to` association for the user
      factory :post do
        title "Through the Looking Glass"
        user
      end
    
      # user factory without associated posts
      factory :user do
        name "John Doe"
    
        # user_with_posts will create post data after the user has been created
        factory :user_with_posts do
          # posts_count is declared as a transient attribute and available in
          # attributes on the factory, as well as the callback via the evaluator
          ignore do
            posts_count 5
          end
    
          # the after(:create) yields two values; the user instance itself and the
          # evaluator, which stores all values from the factory, including transient
          # attributes; `create_list`'s second argument is the number of records
          # to create and we make sure the user is associated properly to the post
          after(:create) do |user, evaluator|
            create_list(:post, evaluator.posts_count, user: user)
          end
        end
      end
    end
    

    在您的情况下,您需要使用 before_create 而不是 after_create 来满足您的验证。

    【讨论】:

      猜你喜欢
      • 2012-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-28
      • 2014-02-11
      • 2023-03-19
      • 2023-03-17
      相关资源
      最近更新 更多