Load and use fixture in rails console

前端 未结 6 1824
南方客
南方客 2021-01-31 08:07

I wonder if there\'s a way to load and/or use fixture in rails console. Actually, I\'d like to create a user from my fixture users.yml to do some testing without ha

6条回答
  •  北荒
    北荒 (楼主)
    2021-01-31 08:44

    So I had a similar but slightly different need. I wanted to use my existing fixtures (from my rspec test) to populate my development database. This is how I did it by adding a new task to my rake file (located in libs/tasks/*.rake):

    task d_populate: :environment do
      require 'active_record/fixtures'
      fixtures_dir = File.join(Rails.root, '/spec/fixtures') #change '/spec/fixtures' to match your fixtures location
      Dir.glob(File.join(fixtures_dir,'*.yml')).each do |file|
      base_name = File.basename(file, '.*')
      puts "Loading #{base_name}..."
      ActiveRecord::Fixtures.create_fixtures(fixtures_dir, base_name)
      end
    end
    

    If you combine this with a db:reset you can populate your development environment at will by adding this to your rake task as well:

    task reseed: [:environment, 'db:reset', 'db:d_populate']
    

    Then you can call rake db:reseed to populate from fixture YAML files.

提交回复
热议问题