Hello Guys,
Wondering about how to create fixtures from tables? Here is the simple task which generate .yml from database tables.
namespace :db do
desc 'Generate .yml test fixtures from an existing database'
task :generate_fixtures => :environment do
sql = "Select * From %s"
skip_tables = ["schema_migrations"]
ActiveRecord::Base.establish_connection
tables = ActiveRecord::Base.connection.tables - skip_tables
tables.each do |table_name|
count = "0000"
File.open("#{RAILS_ROOT}/db/fixtures/#{table_name}.yml", 'w') do |file|
table_content = ActiveRecord::Base.connection.select_all(sql % table_name)
file.write table_content.inject({}) { |hash, record|
hash["#{table_name}_#{count.succ!}"] = record
hash
}.to_yaml
end
end
end
end
desc 'Generate .yml test fixtures from an existing database'
task :generate_fixtures => :environment do
sql = "Select * From %s"
skip_tables = ["schema_migrations"]
ActiveRecord::Base.establish_connection
tables = ActiveRecord::Base.connection.tables - skip_tables
tables.each do |table_name|
count = "0000"
File.open("#{RAILS_ROOT}/db/fixtures/#{table_name}.yml", 'w') do |file|
table_content = ActiveRecord::Base.connection.select_all(sql % table_name)
file.write table_content.inject({}) { |hash, record|
hash["#{table_name}_#{count.succ!}"] = record
hash
}.to_yaml
end
end
end
end
For more information follow http://ar.rubyonrails.org/classes/Fixtures.html
create_fixtures(fixtures_directory, table_names, class_names = {}) is the inbuilt method available to create fixtures for testing.
No comments:
Post a Comment