3

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:

  • I am using gitlab CI for running CI and deployment
  • rails version - 5.2
  • rspec version 3
Sigu Magwa
  • 546
  • 5
  • 18
  • You could write a simple spec that runs `rails db:seed` and write expectations about the return value and maybe the database mutations that occur. – max Aug 14 '18 at 17:57
  • How do you run `rails db:seed ` from within rspec tests? I am aware of using FactoryBot but not seed files – Sigu Magwa Aug 14 '18 at 18:00
  • 1
    `expect(system("rails db:seed")).to be_truthy` - see https://stackoverflow.com/questions/6338908/ruby-difference-between-exec-system-and-x-or-backticks for plenty of other options on how to run it. – max Aug 14 '18 at 18:02
  • There are also more fancy ways of testing rake tasks (`"rails db:seed"` is really just an alias of "rake db:seed"). https://robots.thoughtbot.com/test-rake-tasks-like-a-boss – max Aug 14 '18 at 18:07

2 Answers2

2

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+).

max
  • 96,212
  • 14
  • 104
  • 165
1

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).

matthewd
  • 4,332
  • 15
  • 21