Auto-load the seed data from db/seeds.rb with rake

前端 未结 7 1306
谎友^
谎友^ 2020-12-14 08:17

I\'m using rails-rspec gem and I have several specs (models, controllers, etc). When I run:

bundle exec rake

everything is te

相关标签:
7条回答
  • 2020-12-14 09:19

    I set up my rake spec task to automatically load db/seeds.rb, so I depend on that for setting up the database for a first run. Add this to your Rakefile:

    task :spec     => "db:seed"
    task :cucumber => "db:seed"
    

    Then, on subsequent runs I just call rspec spec directly to skip the seed step and avoid unnecessary reloading. I configure database cleaner to ignore the seed tables like this:

    RSpec.configure do |config|
    
      config.add_setting(:seed_tables)
      config.seed_tables = %w(countries roles product_types)
    
      config.before(:suite) do
        DatabaseCleaner.clean_with(:truncation, except: config.seed_tables)
      end
    
      config.around(:each) do |example|
        if example.metadata[:no_transactions]
          DatabaseCleaner.strategy = :truncation, {except: config.seed_tables}
        else
          DatabaseCleaner.strategy = :transaction
        end
        DatabaseCleaner.start
        example.run
        DatabaseCleaner.clean
      end
    end
    

    For scenarios that need committed data, I can add:

    describe "commit for real", use_transactions: false do
      # ...
    end
    

    This will truncate everything after the example runs, except the seed tables. It's assumed that you never write anything to the seed tables! This is generally a safe assumption, since seed data is typically static.

    For all other normal scenarios, I depend on transactions to roll back any inserted records. The database is returned to the original state, with the data in the seed tables intact. It's safe to write to the seed tables here if you need to.

    To rebuild the seed tables, you just need to run rake spec again.

    0 讨论(0)
提交回复
热议问题