How to seed test databases in Rails

Assuming we’re using RSpec, we can call Rails.application.load_seed in a before(:suite) hook inside spec_helper.rb or wherever else you configure RSpec.

RSpec.configure do
  config.before :suite do
    Rails.application.load_seed
  end
end

This will automatically run our db/seeds.rb just once at the start of every test run.

Now, we don’t have to keep running RAILS_ENV=test db:seed whenever our seed logic changes.

You’ll want to make sure you put in appropriate checks to avoid re-running the same seeds every time. So something like:

def seed
  # Create bunch of users
end

seed if User.count.zero?

Yay!

Sajad Torkamani

Hello! My name is Sajad. I’m a software developer at Nationwide and an aspiring entrepreneur. Originally from Afghanistan, I moved to London at an early age and have been living here for the past 20 years.

This is my personal website where I blog mostly about programming with occasional thoughts on a bunch of other things. I write mainly for my own benefit as I find that writing helps clarify my otherwise very confused thoughts.

Get in touch: sajadtorkamani1@gmail.com