Search code examples
ruby-on-railstestingtddbddfixtures

Is there a way to generate Rails fixtures from an existing set of models?


I have a Rails 2.x app with no tests. I can write out the tests manually, but is there a way to generate fixtures automatically? It would be nice to not have to type all that out by hand.

I could run script/generate again for all the models, but everything already exists and if I understand generators correctly, I'd still have to type in all the attributes.

I thought about running the Rails console and doing for example...

>> y VendorUser.all.rand

That would give me some YAML with all the attributes, but they'd be out of order and it's still pretty time-consuming.

Can anyone suggest a more efficient option?


Solution

  • Here is a rake task to generate fixtures.

    desc "extracting data for fixtures"
    task :extract_fixtures => :environment do
      sql  = "SELECT * FROM %s"
      skip_tables = ["schema_info","schema_migrations"]
      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