How to create mock data of STI in RSpec 【Ruby on Rails】

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.

My LinkedIn account is below! Please contact me!

https://www.linkedin.com/in/tomoharu-tsutsumi-56051a126/

--

--

Tomoharu Tsutsumi
Tomoharu Tsutsumi

Written by Tomoharu Tsutsumi

5+ years Full Stack SWE (Ruby, Go, TypeScript, JavaScript) | Former Founding Engineer of AI Startup in Canada

No responses yet