Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-8 of 8 total  RSS 

Synchronizing Rails DB Contents via Fixtures

The following rake task will dump the contents of the current environment's database to YAML fixtures. Stick the following in lib/tasks/fixtures.rake:

namespace :db do
  namespace :fixtures do
    
    desc 'Create YAML test fixtures from data in an existing database.  
    Defaults to development database.  Set RAILS_ENV to override.'
    task :dump => :environment do
      sql  = "SELECT * FROM %s"
      skip_tables = ["schema_info"]
      ActiveRecord::Base.establish_connection(:development)
      (ActiveRecord::Base.connection.tables - skip_tables).each do |table_name|
        i = "000"
        File.open("#{RAILS_ROOT}/test/fixtures/#{table_name}.yml", 'w') do |file|
          data = ActiveRecord::Base.connection.select_all(sql % table_name)
          file.write data.inject({}) { |hash, record|
            hash["#{table_name}_#{i.succ!}"] = record
            hash
          }.to_yaml
        end
      end
    end
  end
end


After making changes to the database that you'd like to dump to fixtures:

rake db:fixtures:dump


After checking out updated fixtures from SVN:

rake db:migrate
rake db:fixtures:load

All Fixtures

def self.all_fixtures(options={})
  fixtures Dir.entries(RAILS_ROOT + '/test/fixtures').select {|f| f =~ /^\w+/ }.collect {|f| f.sub!(/.yml$/,'').to_sym }.reject {|i| [*options[:except]].include? i }
end

DRYing up YAML fixtures

// Rails Recipes explained how to DRY up the database configuration code. I applied the same idea to user fixtures, which worked while we used MySQL. Once on Postgres, "defaults" started throwing an error. The easiest solution was to make quentin's values the 'defaults'

quentin: &defaults
  id: 1
  login: quentin
  email: quentin@example.com
  site_id: 1
  salt: 7e3041ebc2fc05a40c60028e2c4901a81035d3cd
  crypted_password: 00742970dc9e6319f8019fd54864d3ea740f04b1 # test
  created_at: <%= 5.days.ago.to_s :db %>
  activated_at: <%= 5.days.ago.to_s :db %> # only if you're activating new signups
aaron:
  id: 2
  login: aaron
  email: aaron@example.com
  activation_code: aaronscode
  site_id: 1
  <<: *defaults
#etc...

Create YAML test fixtures from database in Rails

As found at http://media.pragprog.com/titles/fr_rr/code/CreateFixturesFromLiveData/lib/tasks/extract_fixtures.rake

desc 'Create YAML test fixtures from data in an existing database.  
Defaults to development database.  Set RAILS_ENV to override.'

task :extract_fixtures => :environment do
  sql  = "SELECT * FROM %s"
  skip_tables = ["schema_info"]
  ActiveRecord::Base.establish_connection
  (ActiveRecord::Base.connection.tables - skip_tables).each do |table_name|
    i = "000"
    File.open("#{RAILS_ROOT}/test/fixtures/#{table_name}.yml", 'w') do |file|
      data = ActiveRecord::Base.connection.select_all(sql % table_name)
      file.write data.inject({}) { |hash, record|
        hash["#{table_name}_#{i.succ!}"] = record
        hash
      }.to_yaml
    end
  end
end

Generate Rails fixture skeleton using ActiveRecord

In Rails 1.1.5, the basic generator generates the following code for the fixture used in database unit tests:
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
first:
  id: 1
another:
  id: 2


As ActiveRecord provides database reflexion features, we can generate a fixture file with all the columns' name prepopulated for number and text types, such as:
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
first:
  id: 1
  short_title: short_title_first
  title: title_first


This will be done by the following class:
require_gem 'activerecord'

class RailsFixturesGenerator

  def generate(class_name)
    
    # Get the "Class" object from the class name        
    model_class = Object.const_get(class_name)
    
    yaml_content =  "# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html\n"
    yaml_content += "first:\n"
    
    # get if first!   
    model_class.columns.each { |column|
      
      yaml_content += "  " + column.name + ": "
      
      if column.number?
        yaml_content +=  "1"
      end
      if column.text?
        # @todo /!\ max length
        yaml_content +=  column.name + "_first"
      end
      
      yaml_content += "\n"      
    }  
    
    write_fixture_file(model_class, yaml_content)
    
    yaml_content            
  end  
  
  # Write the <fixture> yaml file  in the test/fixtures folder
  def write_fixture_file(model_class, yaml_content)
    
    path = ENV['DEST'] || "#{RAILS_ROOT}/test/fixtures"
    db   = ENV['DB']   || 'test'
    
    File.open("#{path}/#{model_class.table_name}.yml", 'wb') do |file|    
      file.write yaml_content 
      file.close    
    end
  end
end


Of course, I have an unit test that I wrote before the code ;-)
This was my first "complex" method I wrote in Ruby so please bear with me. Any feedback is welcome. I want to write a Rails plugin in order to share the generators I will write.

Fix for nil object error in Rails test fixtures

If you're seeing errors like this when you run Rails tests:

# NoMethodError: You have a nil object when you didn't expect it!


You might need to edit test/test_helper.rb to make sure use_instantiated_fixtures is true:

self.use_instantiated_fixtures = true


Prior to 1.0, Rails automatically created instance variables out of fixtures. So if you had a fixture record named "foo", you could access it in your test as "@foo". As of 1.0, the default is to disable that feature, which breaks a lot of existing code. Mike Clark explains the change.

loading fixtures to development database

Fixed the previous example so it would load environment first:

desc "Load fixtures data into the development database"
task :load_fixtures_to_development => :environment do
  ActiveRecord::Base.establish_connection(:development)
  require 'active_record/fixtures'
  Fixtures.create_fixtures("test/fixtures", ActiveRecord::Base.configurations[:fixtures_load_order])
  puts "Loaded these fixtures: " + ActiveRecord::Base.configurations[:fixtures_load_order].collect { |f| f.to_s }.join(', ')
end


This requires a fixture list in database.yml (or you can specify in environment.rb if you wish:

:fixtures_load_order:
  - :fixture_1
  - :fixture_2
  - :fixture_3
  - :fixture_4
  - :fixture_5

Loading data from fixtures in development mode

By Tim Bates.

desc "Load fixtures data into the development database"
task :load_fixtures_data_to_development do
   require 'active_record/fixtures'
   ActiveRecord::Base.establish_connection(
       ActiveRecord::Base.configurations["development"])
   Fixtures.create_fixtures("test/fixtures",
       ActiveRecord::Base.configurations[:fixtures_load_order])
end
« Newer Snippets
Older Snippets »
Showing 1-8 of 8 total  RSS