如何在Rails 5.2上使用FactoryBot测试多态关联?

问题描述 投票:0回答:1

我编写基本测试以指定在模型级别进行的验证。我使用Rspec和FactoryBot。BusinessObject模型可以有两个父对象:BusinessArea或BusinessProcess。

BusinessObject模型的摘录:

# == Schema Information
#
# Table name: business_objects
#
#  id                 :integer          not null, primary key
#  playground_id      :integer          not null
#  main_scope_id      :integer
#  code               :string(30)       not null
#  name               :string(200)      not null
#  description        :text
#  area_process_type  :string
#  area_process_id    :integer

class BusinessObject < ActiveRecord::Base
  belongs_to :area_process, polymorphic: true
  validates :area_process, presence: true
...
end

BusinessArea模型的摘录:

class BusinessArea < ActiveRecord::Base
  has_many :business_objects, as: :area_process
...
end

BusinessProcess模型的摘录:

class BusinessProcess < ActiveRecord::Base
  has_many :business_objects, as: :area_process
...
end

[工厂:

FactoryBot.define do
  factory :business_object do
    association :area_process,  factory: :business_area
    name                {"Test Business Object"}
    code                {"TEST_BO"}
    description         {"This is a test Business object used for unit testing"}
    created_by          {"Fred"}
    updated_by          {"Fred"}
    owner_id            {1}
    status_id           {0}
    end

end

[运行测试时,工厂失败,并显示以下消息:

7)BusinessObject具有有效的工厂失败/错误:expect(build(:business_object))。to be_valid

 ActiveRecord::StatementInvalid:
   PG::UndefinedColumn: ERROR:  Column business_objects.business_area_id does not exist.

如何向工厂指定要在关联中使用的父级?

非常感谢!

ruby-on-rails factory-bot
1个回答
0
投票

由于Factory Bot cheatsheet,我找到了作为子工厂声明的解决方案。

定义工厂时,我必须指定业务对象的父项:

FactoryBot.define do
  factory :business_object, parent: :business_area do
    playground_id       {0}
    name                {"Test Business Object"}
    code                {"TEST_BO"}
    description         {"This is a test Business object used for unit testing"}
    created_by          {"Fred"}
    updated_by          {"Fred"}
    owner_id            {1}
    status_id           {0}
  end
end

然后,工厂在创建测试的业务对象时会引用必需的父级。

© www.soinside.com 2019 - 2024. All rights reserved.