Database configuration using rspec-rails

0

In my spec / rails_helper.rb I added the following code so that the database was automatically created when running rspec :

def database_exists?
  ActiveRecord::Base.connection rescue ActiveRecord::NoDatabaseError ? false : true
end
unless database_exists?
  ActiveRecord::Base.establish_connection(:"#{ENV['RAILS_ENV']}")
  db_config = ActiveRecord::Base.configurations[ENV['RAILS_ENV']]
  ActiveRecord::Base.connection.create_database db_config
end

But when I run rspec I get the following error:

  

.rbenv / versions / 2.2.1 / lib / ruby / gems / 2.2.0 / gems / activerecord-4.2.1 / lib / active_record / connection_adapters / mysql2_adapter.rb: 23: in 'rescue in mysql2_connection': Unknown database 'my-db-test' (ActiveRecord :: NoDatabaseError)

Could not create the database?

If I put system('rake db:create') works, but is it good practice to do this?

    
asked by anonymous 24.04.2015 / 21:00

1 answer

1

There is a rake task to prepare the test bench:

bundle exec rake db:test:prepare

This command creates the database, runs the migrations, and loads the schema. From there you can run the test suite.

    
27.04.2015 / 08:19