Use your seeds.rb as fixtures when running tests.
Read the back story of this gem: https://ghiculescu.substack.com/p/using-realistic-development-and-test
Currently only Rails 7 and up is supported. PRs to support older Rails versions are welcome!
-
Add
seed_fixturesto thetestgroup of your Gemfile, then runbundle install. -
In your
test_helper.rb:
class ActiveSupport::TestCase
# Add this line:
fixtures_from_seeds
# Comment out or remove this line:
# fixtures :all
endNotes:
- You cannot use standard Rails fixtures if you are using this gem. Make sure you remove the
fixturescall that's included intest_helper.rbby default! - Ensure your
test_helper.rbincludes this:require "rails/test_help".
- Add
.seeds_hashto your.gitignorefile.
- When tests run, the contents of
db/seeds.rbwill be loaded into the test database. - To improve performance, keeps a hash of everything your app's
db/folder in the.seeds_hashfile. This way, seeds are only reloaded into the database if you change your seeds file or your schema. - Adds a
parallel_setuphook, so if you run parallel tests, seeds will be loaded correctly. (This is needed because parallel databases are truncated before each run.)
Just like anything else in the database...
user = User.find_by(name: "Alex")Or if you like, define helper methods for easy lookup.
module SeedFixtureLookups
def user_alex
@user_alex ||= User.where(name: "Alex").sole
end
end
class ActiveSupport::TestCase
include SeedFixtureLookups
end
# in a test...
test "alex exists" do
assert_not_nil user_alex
endNot everyone agrees this gem is a good idea. And for many apps, it's not! But for some apps it is a very neat way of writing a robust test suite. If your app is one of those, give this a try.
There's more back story on the gem here: https://ghiculescu.substack.com/p/using-realistic-development-and-test
The gem is available as open source under the terms of the MIT License.