methyl
methyl

Reputation: 3312

Best way to fill development db in rails

I need to fill the test development database with data, for example from factorygirl, but I'd like to use it from rails console.
How I put example data in db so I can fetch it from console and do some test there?

Upvotes: 17

Views: 8473

Answers (4)

leflings
leflings

Reputation: 646

Faker is also a good solution.

Here's how my lib/tasks/sample_data.rake looks like. I run it with rake db:populate.

Creates 50 entries with random info.

require 'faker'

namespace :db do
  desc "Fill database with sample data"
  task :populate => :environment do
    Rake::Task['db:reset'].invoke
    50.times do |n|
      name  = Faker::Company.name
      year = 1900+rand(111)
      rating = 1+rand(10)
      watched = (1 == rand(2) ? true : false)
      imdb_id = rand(1000000)
      Movie.create!(:name => name,
                    :year => year,
                    :rating => rating,
                    :watched => watched,
                    :imdb_id => imdb_id)
    end
  end
end

Upvotes: 18

Douglas Drouillard
Douglas Drouillard

Reputation: 785

Michael Hartl provides an excellent introduction to this topic as part of the railstutorial.org program.

He uses a gem called Factory Girl, which is designed to ease the process of populating a database with sample data.

E.G.

http://ruby.railstutorial.org/chapters/user-microposts#sec:sample_microposts

https://github.com/railstutorial/sample_app/blob/master/lib/tasks/sample_data.rake

Upvotes: 2

Nerian
Nerian

Reputation: 16177

Is it just in the Rails console or just 'from the console'?

I like to use a Thor or Rake task to do that. Instead of Factory Girl I use Machinist.

You may want to check this answer

Rails: Good Rspec2 example usage? (Also: Cucumber, Pickle, Capybara)

Upvotes: 1

tadman
tadman

Reputation: 211600

I've made a gem test_dummy that works like Factory Girl to define lots of fake data. When properly configured you can do things like this:

# Create 100 fake companies
100.times { Company.create_dummy }

# Create a single fake company on-demand
fake_company = Company.create_dummy

The alternative is to use the db/seeds.rb facility or to load in your fixtures into your development environment.

Upvotes: 2

Related Questions