简体   繁体   中英

How can I access to a child class instead of parent class in a 'callback' function of factorybot in ruby on rails?

I have implemented a STI in ROR. please look at the following code:

class Category < ApplicationRecord
end

class CourseCategory < Category
  has_many :courses
end

I use FactoryBot to create data like this:

# category

FactoryBot.define do
  factory :category do
    name {"Ruby on Rails"}
  end
end

# course_category

FactoryBot.define do
  factory :course_category, parent: :category, class: 'Category' do
    trait :with_course do
      after(:create) do |course_category| # my problem is here
      create :course, :with_steps, course_category: course_category
    end
  end
end

# course

FactoryBot.define do
  factory :course do
     course_category
  end
end

while I run FactoryBot.create(:course_category, :with_course) , into trait :with_course , I should have CourseCategory class, but I receive Category .

Can I have access to parent class instead of child class into a callback of FactoryBot?

Your factory is building :course_category as the wrong class.

This line needs to be changed...

factory :course_category, parent: :category, class: 'Category' do

Into...

factory :course_category, parent: :category, class: 'CourseCategory' do

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM