How to create mock data of STI in RSpec 【Ruby on Rails】
Feb 21, 2023
When your application has STI data, this method is necessary to test it.
Modal Structure
class Music
# some codes
end
class Jazz < Music
# some codes
# this class has the "type" column and the value is "Jazz"
end
Factory
In this case, you might write codes like this.
FactoryBot.define do
factory :music do
title { Faker::Music.title }
end
trait :jazz do
type 'Jazz'
end
end
However, this codes are going to create the instance of music, not jazz
create :music, :jazz
You have to write tricky codes to solve this problem.
Solution
FactoryBot.define do
factory :music do
title { Faker::Music.title }
end
trait :jazz do
type 'Jazz'
initialize_with do
klass = type.constantize
klass.new(attributes)
end
end
end
It is necessary to use initialize_with.