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.connection.tables - skip_tables).each do |table_name| 
      #("users").each do |table_name| 
        i = "000" + "/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 



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


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: