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

前端 未结 7 1305
谎友^
谎友^ 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:02

    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
    
    0 讨论(0)
  • 2020-12-14 09:08

    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.

    0 讨论(0)
  • 2020-12-14 09:12

    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
    
    0 讨论(0)
  • 2020-12-14 09:13

    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.

    0 讨论(0)
  • 2020-12-14 09:14
    1. copy the seed.rb file inside the config/initializers folder.So seed.rb file will be executed on server start.

    2. Run the below command to fill the test db with the seed.rb data

      RAILS_ENV=test rake db:seed

    0 讨论(0)
  • 2020-12-14 09:18

    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" 
    
    0 讨论(0)
提交回复
热议问题