Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby-on-rails: Seeding-data strategies (or loading test data into developer database)

I want to clear and re-load my developer database (Ruby on rails) frequently.

Of course, I can manually add the data via the web page but I was wondering if anyone has any strategies for this type of testing.

(I already have unit, functional and integration tests, fyi)

Thanks

like image 775
cbrulak Avatar asked Sep 21 '26 05:09

cbrulak


2 Answers

Create a seed.yml file in db directory. Add a YAML document for each model you want to create. This document should contain a list of hash. Each hash should contain model attributes.

  users:
      -   login: jake
          password: jake123
          password_confirmation: jake123
          first_name: Jake
          last_name: Driver

      -   login: Jane
          password: jane123
          password_confirmation: jane123
          first_name: Jane
          last_name: McCain

  categories:

  products:

In your seed.rb file

seed_file = File.join(Rails.root, 'db', 'seed.yml')
config = YAML::load_file(seed_file)
User.transaction do 
  config.keys.each{ |key| key.classify.constantize.create(config[key]) }
end

I find it easier to modify the seed data in the YML file. Application that I have built is deployed by a different team. They like this approach too.

To clear the data I have a rake task in lib\tasks directory. I run the rake task as app:flush.

namespace :app do
  desc "Flush all the seed data "
  task :flush => :environment do
    config = YAML::load_file(File.join(Rails.root, 'db', 'seed.yml'))
    User.transaction do 
      config.keys.each{ |table| truncate_table(table)}
    end
  end
end
like image 135
Harish Shetty Avatar answered Sep 23 '26 22:09

Harish Shetty


Time to look at "fixtures" and "seeding data" ;-) I am not good enough to give you a clear explanation, but googling those two keys should give you all you need.

Check these out: http://derekdevries.com/2009/04/13/rails-seed-data/
http://lptf.blogspot.com/2009/09/seed-data-in-rails-234.html

like image 41
Trevoke Avatar answered Sep 23 '26 22:09

Trevoke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!