I\'m using rails-rspec
gem and I have several specs (models, controllers, etc). When I run:
bundle exec rake
everything is te
To load seeds in rspec you need to add it after database cleanup in confg.before(:suite) in spec_helper
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
load "#{Rails.root}/db/seeds.rb"
end
Bad idea! Never, ever, seed your test database. Use factories to create, within each test, only the records necessary for that test to pass. Seeding the test database will make your tests less reliable, because you'll be making lots of assumptions that aren't explicitly stated in your tests.
In Rails 4.2.0 and RSpec 3.x, this is how my rails_helper.rb looks.
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = false
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each, :js => true) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
config.before(:all) do
Rails.application.load_seed # loading seeds
end
end
I think we should use
config.before(:each) do
Rails.application.load_seed # loading seeds
end
as before(:all) runs the block one time before all of the examples are run.
So if we use before :all
, the seed data will be cleared.
copy the seed.rb file inside the config/initializers folder.So seed.rb file will be executed on server start.
Run the below command to fill the test db with the seed.rb data
RAILS_ENV=test rake db:seed
Depending on how your seed file is configured, you might just be able to load/run it from a before(:each)
or before(:all)
block:
load Rails.root + "db/seeds.rb"