Sigu Magwa
Sigu Magwa

Reputation: 568

Testing validity of database seed file in rails

Seed files can become invalid fast as code grows. I just had a situation where the open merge request had all tests running and passing but when I run rails db:seed on staging server failed as the seed file did not have all the required fields for that particular model. Is there a way we can always test for validity of the seed file?

Maybe relevant:

Upvotes: 3

Views: 711

Answers (2)

max
max

Reputation: 101831

Turns out its actually dead simple to test with RSpec:

require 'rails_helper'
RSpec.describe "db:seed" do
  it "works" do
    expect { Rails.application.load_seed }.to_not raise_error
  end
  it "creates a foo" do
    expect { Rails.application.load_seed }.to change(Foo, :count)
  end
end

Which can kind of be expected since "seeding" really just involves requiring a single ruby file.

Rails.application.load_seed is used by the rake db:seed task (aka rails db:seed in Rails 5+).

Upvotes: 2

matthewd
matthewd

Reputation: 4420

You can define a separate CI task that runs rails db:seed, next to your existing one that runs rspec (or rails spec, or whatever spelling it uses).

Upvotes: 1

Related Questions