Archive for June, 2012

Generating Fixtures from your Test DB (Rails 3.1)

If you’re like me and figuring out rails as you go, you likely have a lot of code without proper test coverage yet.  Well, now it’s time to build a test suite because smoke testing in Chrome just won’t cut it anymore.

Since my app has a pretty complex series of models, it’s a pain in the ass to create fixtures manually, so I did some googling and found a nifty little rake task to help.  It’s a great starting point to get that test suite built out.

I’ve updated it to work with Rails 3.1.  Hope it helps.

#put 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_migrations"] 
      ActiveRecord::Base.establish_connection(:development) 
      (ActiveRecord::Base.connection.tables - skip_tables).each do |table_name| 
      #("users").each do |table_name| 
        i = "000" 
        File.open(Rails.root.to_s + "/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

Cheers,

Zach

PS: If you want to insert code snippets into a wordpress.com hosted WP, use sourcecode tags and not a gist… understandably, WP, does not like script tags in posts.