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

I have a Rails 2.x application without tests. I can write tests manually, but is there a way to automatically create fixtures? It would be nice not to enter all this manually.

I can run the script / generate again for all models, but everything already exists, and if I understand the generators correctly, I still have to enter all the attributes.

I was thinking about starting the Rails console and for example ...

>> y VendorUser.all.rand

That would give me some YAML with all the attributes, but they would be out of order, and that is still quite a lot of time.

Can anyone suggest a more efficient option?

+3
source share
1 answer

Here is the rake task for creating 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
+4
source

All Articles