ruby-on-rails - test - rspec--seed




With RSpec, how to seed the database on load? (4)

I'm using rspec for testing w my rails 3 app. I need to seed the database before the tests start. How can I seed the database with the following:

/db/seeds.rb

["Admin", "Member"].each do |role_name|
  Role.find_or_create_by_name(role_name)
end

Thanks


However Scott's solution surely works for you, I believe the better way to solve your problem was to put the code responsible for seeding your test database within RSpec's configure block:

I use SeedFu and in my spec_helper I have:

RSpec.configure do |config|

  # some other configuration code ...

  config.before(:suite) do
    # ...
    SeedFu.seed
    # ...
  end

  # some other configuration code ...

end

I ended up needing to use DatabaseCleaner to truncate the database, then load the rake task that does my seeding (because I use seedbank). After that, I wound up wrapping my tests in a transaction like on the database_cleaner README, so that each test could run with a freshly loaded site.

RSpec.configure do |config|
  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(:truncation)
    MyApplicationName::Application.load_tasks
    Rake::Task['db:seed'].invoke # loading seeds
  end
  config.around(:each) do |example|
    DatabaseCleaner.cleaning do
      example.run
    end
  end
end

In spec_helper.rb:

RSpec.configure do |config|
  config.before(:suite) do
    Rails.application.load_seed # loading seeds
  end
end

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




rspec