Rails做单元测试时,我们自己手动去创建所有的fixtures会是个噩梦,有没有什么好的方案呢?
我们可以利用数据库里已有的数据,写一个rake tast来把数据库的数据复制出来到YAML文件里:
CreateFixturesFromLiveData/lib/tasks/extract_fixtures.rake
[code]
desc 'Create YAML test fixtures from data in an existing database.
Defaults to development database. Set RAILS_ENV to override.'
task :extract_fixtures => :environment do
sql = "SELECT * FROM %s"
skip_tables = ["schema_info"]
ActiveRecord::Base.establish_connection
(ActiveRecord::Base.connection.tables - skip_table).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
[/code]
好了,现在我们运行[b]rake extract_fixtures[/b],则test/fixtures/目录下将生成每个表的数据的yml文件
我们可以利用数据库里已有的数据,写一个rake tast来把数据库的数据复制出来到YAML文件里:
CreateFixturesFromLiveData/lib/tasks/extract_fixtures.rake
[code]
desc 'Create YAML test fixtures from data in an existing database.
Defaults to development database. Set RAILS_ENV to override.'
task :extract_fixtures => :environment do
sql = "SELECT * FROM %s"
skip_tables = ["schema_info"]
ActiveRecord::Base.establish_connection
(ActiveRecord::Base.connection.tables - skip_table).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
[/code]
好了,现在我们运行[b]rake extract_fixtures[/b],则test/fixtures/目录下将生成每个表的数据的yml文件