開発データベースに、テスト環境のフィクスチャとして利用したいデータがいくつかあります。Rails 2.xでデータベーステーブルをYAMLフィクスチャにエクスポートするための最良の方法は何ですか?
11 に答える
これには rake タスクがあります。必要に応じて RAILS_ENV を指定できます。デフォルトは開発環境です。
rake db:fixtures:dump
# Create YAML test fixtures from data in an existing database.
データベースの状態を保存するために YamlDb を使用しています。
次のコマンドでインストールします。
script/plugin install git://github.com/adamwiggins/yaml_db.git
rake タスクを使用して、Rails データベースの内容を db/data.yml にダンプします。
rake db:data:dump
rake タスクを使用して、db/data.yml の内容をデータベースにロードします。
rake db:data:load
これはクリエイターのホームページです。
http://blog.heroku.com/archives/2007/11/23/yamldb_for_databaseindependent_data_dumps/
このプラグインはあなたが望む機能を追加します。ActiveRecordから抽出されたため、デフォルトでは提供されなくなりました。
script/plugin install http://github.com/topfunky/ar_fixtures
次に、以下を実行します。
rake db:fixtures:dump MODEL=ModelName
Rails 3の場合、DBからyamlをダンプしてフィクスチャとして使用する場合は、次のコードを使用します。
module DbToFixture
TEMP_FIXTURE_PATH = Rails.root.join("test", "new_fixtures")
def fixturize(model)
Dir.mkdir(TEMP_FIXTURE_PATH) unless File.exists?(TEMP_FIXTURE_PATH)
fname = model.table_name
file_path = TEMP_FIXTURE_PATH.join(fname)
File.open(file_path, 'w') do |f|
model.all.each do |m|
f.write(m.to_yaml)
end
end
end
end
コンソールから実行するだけです
require './lib/db_to_fixture'
include DbToFixture
fixturize ModelName
ar_fixturesをRails3で動作させることができませんでした(ただし、あまり頑張っていません)。Yaml dbは、dbのダンプと保存に最適ですが、その形式はフィクスチャと互換性がありません。
rake db:fixtures:dump
に変更されました
rake db:extract_fixtures
これを正確に実行するrakeタスクは次のとおりです(Rails 3.2.8でテスト済み):
namespace :db do
task :extract_fixtures => :environment do
sql = 'SELECT * FROM "%s"'
skip_tables = ["schema_migrations"]
ActiveRecord::Base.establish_connection
if (not ENV['TABLES'])
tables = ActiveRecord::Base.connection.tables - skip_tables
else
tables = ENV['TABLES'].split(/, */)
end
if (not ENV['OUTPUT_DIR'])
output_dir="#{Rails.root}/test/fixtures"
else
output_dir = ENV['OUTPUT_DIR'].sub(/\/$/, '')
end
(tables).each do |table_name|
i = "000"
File.open("#{output_dir}/#{table_name}.yml", 'w') do |file|
data = ActiveRecord::Base.connection.select_all(sql % table_name.upcase)
file.write data.inject({}) { |hash, record|
hash["#{table_name}_#{i.succ!}"] = record
hash
}.to_yaml
puts "wrote #{table_name} to #{output_dir}/"
end
end
end
end
出典:http ://sachachua.com/blog/2011/05/rails-exporting-data-specific-tables-fixtures/
注:ブログコードにいくつかの変更を加えて、データベース間の互換性を高め、Rails3.2で機能させる必要がありました。
Rails 6でこれを使用しました:
# How to run:
# rake fixtures:import_db_table[my_table]
namespace :fixtures do
desc 'Convert development table into Rails test fixtures'
task :import_db_table, [:table_name] => :environment do |_task, args|
begin
table_name = args[:table_name]
raise "Missing table name" if table_name.blank?
conter = '000'
file_path = "#{Rails.root}/spec/fixtures/#{table_name}.yml"
ActiveRecord::Base.establish_connection
File.open(file_path, 'w') do |file|
rows = ActiveRecord::Base.connection.select_all("SELECT * FROM #{table_name}")
data = rows.each_with_object({}) do |record, hash|
suffix = record['id'].blank? ? conter.succ! : record['id']
hash["#{table_name.singularize}_#{suffix}"] = record
end
puts "Writing table '#{table_name}' to '#{file_path}'"
file.write(data.to_yaml)
end
ensure
ActiveRecord::Base.connection.close if ActiveRecord::Base.connection
end
end
end
ここから抽出されます(すべてのテーブルをインポートします)。
For dumping for rspec/cucumber test fixtures in Rails 3 this is the best answer I've found: What is the standard way to dump db to yml fixtures in rails?