【问题标题】:Factory Bot associations with namespaced model glitchingFactory Bot 与命名空间模型故障的关联
【发布时间】:2019-03-06 20:57:19
【问题描述】:

在尝试构建命名空间关联时,Factorybot 不会注册命名空间,而是使用自己的命名空间,尽管它就像文档一样定义(并且 SO 上的每个线程都说)。

型号Admin::TicketCategory

class Admin::TicketCategory < ApplicationRecord has_many :tickets end

及其工厂:

FactoryBot.define do
  factory :ticket_category, class: Admin::TicketCategory do |f|
    f.text { Faker::Commerce.product_name }
  end
end

Ticket 模型:

class Ticket < ApplicationRecord
  belongs_to :user
  belongs_to :service_rep, class_name: 'User', foreign_key: :user_id
  belongs_to :ticket_category
  belongs_to :ticket_status
  belongs_to :ticket_urgency
  has_many :ticket_comments
end

及其工厂:

FactoryBot.define do
  factory :ticket do |f|
    f.user
    f.ticket_category
    f.subject { Faker::Lorem.sentence }
    f.body { Faker::Lorem.paragraph }
    f.ticket_urgency { admin_ticket_urgency }
    f.ticket_status { admin_ticket_status }
    f.service_rep { user }
  end
end

当我尝试验证 Ticket 模型时,出现此错误:

  1) Ticket has a valid factory
 Failure/Error: expect(FactoryBot.create(:ticket)).to be_valid

 NameError:
   uninitialized constant Ticket::TicketCategory

任何帮助将不胜感激!

【问题讨论】:

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


    【解决方案1】:

    在涉及命名空间模型时,rails 的工作原理如下: 它将尝试找出当前命名空间中的关联模型。

    让我们从您定义的关联开始:

    Admin::TicketCategory 中应该有has_many: tickets, class_name: "Ticket"(假设你在Ticket 模型中有ticket_category_id)。在你的Ticket 模型中你应该有belongs_to: ticket_category, class_name: "Admin::TicketCategory

    这应该足以让它工作

    【讨论】:

      猜你喜欢
      • 2013-05-28
      • 1970-01-01
      • 1970-01-01
      • 2012-09-10
      • 2020-11-01
      • 1970-01-01
      • 2019-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多