How to deal with factories in your Rails project you need all the time?
In all of my projects, I have some data that my tests heavily rely on: things like a list of currencies, shipping methods, a pre-defined list of roles, and other things that never change or very infrequently.
When writing tests, I do not want to create the same record from my factories over and over again for each and every test, but instead just have it available. How do you do that?
That’s exactly what Rails’
seeds.rb file is for:
To add initial data after a database is created, Rails has a built-in 'seeds' feature that makes the process quick and easy. This is especially useful when reloading the database frequently in development and test environments. It's easy to get started with this feature: just fill up db/seeds.rb with some Ruby code, and run rails db:seed.
I do exactly that: I create my records there that I'd like to stay permanent to my test, like
Currency.create(acronym: ‘USD’, name: ‘US Dollar’).
Then I execute
RAILS_ENV=test rake db:seed, which will create all records specified in your seeds file in your test database. If you happen to use
database_cleaner, this will work flawlessly with the default configuration for