Ruby-on-rails – Bundle exec rake spec and custom rake tasks


I have a simple rake task, dedicated for populating my postgresql database (same db for dev, test and prod environments):

# lib/tasks.sample_data.rake
namespace :db do
  desc "Fill database with sample data"
  task populate: :environment do

def make_users
 ... users = []; users << User.create(...)

When I use 'bundle exec rake db:populate' this task is working fine. I have full db of User records.

I also have some rspec tests, which are using model User, and a problem with command

bundle exec rake spec

This command for some reason ruins my db and I have the following result of tests:


  1) Lead should return counters hash
     Failure/Error: user = User.find(1)
       Couldn't find User with id=1
     # ./spec/models/lead_spec.rb:23:in `block (2 levels) in <top (required)>'

Finished in 0.16812 seconds

After this rake task I can see that User.count returns 0

I have default Rakefile and here is the list of all my rake tasks:

rake -T

rake about                              # List versions of all Rails frameworks and the environment
rake assets:clean[keep]                 # Remove old compiled assets
rake assets:clobber                     # Remove compiled assets
rake assets:environment                 # Load asset compile environment
rake assets:precompile                  # Compile all the assets named in config.assets.precompile
rake cache_digests:dependencies         # Lookup first-level dependencies for TEMPLATE (like messages/show or comments/_comment.html)
rake cache_digests:nested_dependencies  # Lookup nested dependencies for TEMPLATE (like messages/show or comments/_comment.html)
rake db:create                          # Create the database from DATABASE_URL or config/database.yml for the current Rails.env (use db:create:all to create all dbs in the config)
rake db:drop                            # Drops the database using DATABASE_URL or the current Rails.env (use db:drop:all to drop all databases)
rake db:fixtures:load                   # Load fixtures into the current environment's database
rake db:migrate                         # Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)
rake db:migrate:status                  # Display status of migrations
rake db:populate                        # Fill database with sample data
rake db:rollback                        # Rolls the schema back to the previous version (specify steps w/ STEP=n)
rake db:schema:cache:clear              # Clear a db/schema_cache.dump file
rake db:schema:cache:dump               # Create a db/schema_cache.dump file
rake db:schema:dump                     # Create a db/schema.rb file that can be portably used against any DB supported by AR
rake db:schema:load                     # Load a schema.rb file into the database
rake db:seed                            # Load the seed data from db/seeds.rb
rake db:setup                           # Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the db first)
rake db:structure:dump                  # Dump the database structure to db/structure.sql
rake db:version                         # Retrieves the current schema version number
rake doc:app                            # Generate docs for the app -- also available doc:rails, doc:guides (options: TEMPLATE=/rdoc-template.rb, TITLE="Custom Title")
rake log:clear                          # Truncates all *.log files in log/ to zero bytes (specify which logs with LOGS=test,development)
rake middleware                         # Prints out your Rack middleware stack
rake notes                              # Enumerate all annotations (use notes:optimize, :fixme, :todo for focus)
rake notes:custom                       # Enumerate a custom annotation, specify with ANNOTATION=CUSTOM
rake rails:template                     # Applies the template supplied by LOCATION=(/path/to/template) or URL
rake rails:update                       # Update configs and some other initially generated files (or use just update:configs, update:bin, or update:application_controller)
rake routes                             # Print out all defined routes in match order, with names
rake secret                             # Generate a cryptographically secure secret key (this is typically used to generate a secret for cookie sessions)
rake spec                               # Run all specs in spec directory (excluding plugin specs)
rake spec:models                        # Run the code examples in spec/models
rake stats                              # Report code statistics (KLOCs, etc) from the application
rake time:zones:all                     # Displays all time zones, also available: time:zones:us, time:zones:local -- filter with OFFSET parameter, e.g., OFFSET=-6
rake tmp:clear                          # Clear session, cache, and socket files from tmp/ (narrow w/ tmp:sessions:clear, tmp:cache:clear, tmp:sockets:clear)
rake tmp:create                         # Creates tmp directories for sessions, cache, sockets, and pids

I am interested why this rake spec ruins my db, because when I am using the same task and 'bundle exec rspec' after that tests are passing.

Here is my database.yml:

 adapter: postgresql
 encoding: unicode
 database: pgdb
 pool: 15
 username: **************
 password: **************
 adapter: postgresql
 encoding: unicode
 database: pgdb
 pool: 15
 username: **************
 password: **************
  adapter: postgresql
  encoding: unicode
  database: pgdb
  pool: 15
  username: **************
  password: **************

Thanks in advance!

Best Solution

I had some similar issues with my DB getting wiped whenever I would run the unit tests manually with bundle exec rspec spec, and it turned out to be that it was using the development environment even though I was setting it manually in spec_helper.rb with ENV["RAILS_ENV"] = 'test'.

Now I just explicitly specify RAILS_ENV=test bundle exec rspec spec or you can put that in a script.

See these threads:

rake cucumber and rake spec always use "develop" environment

Rails 4, New App: Why do tests run in development environment? (I tried the Rails.env = 'test' thing and it didn't work for me, but give it a shot)

Related Question