How do I prepare test database(s) for Rails rspec tests without running rake spec?

后端 未结 6 1774
無奈伤痛
無奈伤痛 2020-12-04 14:28

After significant troubleshooting, I figured out that I needed to run rake spec once (I can abort with control-c) before I can run rspec directly (e.g. on a sub

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 14:40

    I had a similar problem setting up the CI system at work, so I gradually worked up a system to handle this. It may not be the best solution, but it works for me in my situation and I'm always on the lookout for better ways to do things.

    I have a test database that I needed setup, but also needed seeded data loaded for our tests to work.

    The basics of troubleshooting rake tasks is to run rake with the --trace option to see what is happening under the hood. When i did this, I found that running rake spec did a number of things that I could replicate (or modify as I saw fit) in a custom rake task.

    Here's an example of what we do.

    desc "Setup test database - drops, loads schema, migrates and seeds the test db"
    task :test_db_setup => [:pre_reqs] do
      Rails.env = ENV['RAILS_ENV'] = 'test'
      Rake::Task['db:drop'].invoke
      Rake::Task['db:create'].invoke
      result = capture_stdout { Rake::Task['db:schema:load'].invoke }
      File.open(File.join(ENV['CC_BUILD_ARTIFACTS'] || 'log', 'schema-load.log'), 'w') { |f| f.write(result) }
      Rake::Task['db:seed:load'].invoke
      ActiveRecord::Base.establish_connection
      Rake::Task['db:migrate'].invoke
    end
    

    This is only an example, and specific to our situation, so you'll need to figure out what needs to be done to get your test db setup, but it is quite easy to determine using the --trace option of rake.

    Additionally, if you find the test setup is taking too long (as it does in our case), you can also dump the database into .sql format and have the test database pipe it directly into mysql to load. We save several minutes off the test db setup that way. I don't show that here because it complicates things substantially -- it needs to be generated properly without getting stale, etc.

    HTH

提交回复
热议问题