Rails做單元測試時,我們自己手動去創(chuàng)建所有的fixtures會是個噩夢,有沒有什么好的方案呢?
我們可以利用數(shù)據(jù)庫里已有的數(shù)據(jù),寫一個rake tast來把數(shù)據(jù)庫的數(shù)據(jù)復(fù)制出來到Y(jié)AML文件里:
CreateFixturesFromLiveData/lib/tasks/extract_fixtures.rake
好了,現(xiàn)在我們運(yùn)行rake extract_fixtures,則test/fixtures/目錄下將生成每個表的數(shù)據(jù)的yml文件
我們可以利用數(shù)據(jù)庫里已有的數(shù)據(jù),寫一個rake tast來把數(shù)據(jù)庫的數(shù)據(jù)復(fù)制出來到Y(jié)AML文件里:
CreateFixturesFromLiveData/lib/tasks/extract_fixtures.rake
- 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
好了,現(xiàn)在我們運(yùn)行rake extract_fixtures,則test/fixtures/目錄下將生成每個表的數(shù)據(jù)的yml文件
安徽新華電腦學(xué)校專業(yè)職業(yè)規(guī)劃師為你提供更多幫助【在線咨詢】