Question

I can imagine it can be very easy just for lazy people like me to populate any fake data to db just with one rake (terminal) command.

I know about Faker, Populator and others but all of them, as far as i can see, need to write some (primitive but) code to make data more human friendly (defining type of random data directly and manually: emalis, names, prices and so on).

It makes sense in most cases but now in my case it would be enough for me to fill mysql varchar fields with any strings, text fields with any long text, int - with numbers and so on

any suggestions?

Was it helpful?

Solution 2

Some example code that shows how to do that:

SKIP_COLUMNS = %w(id created_at updated_at)
RECORDS_COUNT = 10

# random data to fill
int = rand(1..100)
varchar = 'lorem'
text = 'big lorem'

# get models
@models = ActiveRecord::Base.connection.tables.collect {|t| t.underscore.singularize.camelize }
@models.select {|m| m.constantize rescue @models.delete(m) }

# fill in data
@models.map(&:constantize).each do |model|
  model.columns_hash.each do |column|
    next if SKIP_COLUMNS.include?(column.first)

    # column_name = column.first
    # column_type = column.last.type

    RECORDS_COUNT.times do
      record = model.new

      case column.last.type
      when :integer
        record.send("#{column.first}=", int) 
      when :string
        record.send("#{column.first}=", varchar) 
      when :text
        record.send("#{column.first}=", text) 
      end

      record.save!
    end
  end
end

You can put that to rake task.

OTHER TIPS

If speed is your aim, you should do two things:

  • Use an in-memory database for your tests until you get to acceptance testing. In other words, consider something like SQLite for your integration tests (Some might say unit tests) rather than MySQL.
  • Use Factory Girl to generate your fake data. Apparently, the data created by tools like that makes more sense than you prefer, but it is weird to me that you care about that. Regardless, it is a lot faster to use existing tools than to write code that generates gibberish just because you don't want data that look "too good."
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top