How to set up a Rake task for sowing

(This is really a newbie question about Rake and Rails and dependencies in general. Trying to wrap your head around how it all fits together)

Basically, I want a Rake task that acts like seed.rb but is called separately. It adds test data for the development environment, and my seed.rb provides basic data for all environments.

The script, family_seed.rb, uses FactoryGirl to generate some records. It looks like this:

require File.expand_path('../../config/environment', __FILE__)
require './spec/factories'

Family.delete_all
Member.delete_all
zinsser = Factory.create(:family, :last_name=>'Zinsser', :first_name=>'Carl', :sim_id => '500')
blackburn = Factory.create(:family, :last_name=>'Blackburn', :first_name=>'Greg', :sim_id => '501')

It works fine with bundle exec "ruby db/family_seeds.rb", but my question is how to configure it using Rake. Should all this be placed in the Rake task? How could I instead configure a task that will invoke the script, and provided that the Rails development environment is available at the time of its launch? I'm trying not just to get the job done, but to do it in the “right” way.

+3
source share
2 answers

One way to approach this is to create a class or module in lib (this makes writing tests easier and making the code more reusable):

require '../spec/factories'

class FamilySeed

  def self.seed
    raise "Don't run this in production!" if Rails.env.production?

    Family.delete_all
    Member.delete_all
    zinsser = Factory.create(:family, :last_name=>'Zinsser', :first_name=>'Carl', :sim_id => '500')
    blackburn = Factory.create(:family, :last_name=>'Blackburn', :first_name=>'Greg', :sim_id => '501')
  end

end

Then create a rake task, for example:

require 'family_seed'

namespace :seed do
  task :families => :environment do
    FamilySeed.seed
  end
end

, , Family.delete_all Member.delete_all. , , db.

+5

: environment

task :delete_all => :environement do
  require Rails.root.join('spec/factories')
  Family.delete_all
  Member.delete_all
  zinsser = Factory.create(:family, :last_name=>'Zinsser', :first_name=>'Carl', :sim_id => '500')
  blackburn = Factory.create(:family, :last_name=>'Blackburn', :first_name=>'Greg', :sim_id => '501')
end

rake delete_all

+2

Source: https://habr.com/ru/post/1780398/


All Articles