Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

are fixtures loaded when using the sql dump to create a test database

Because of some non standard table creation options I am forced to use the sql dump instead of the standard schema.rb (i.e. I have uncommented this line in the environment.rb config.active_record.schema_format = :sql). I have noticed that when I use the sql dump that my fixtures do not seem to be loaded into the database. Some data is loaded into it but, I am not sure where it is coming from. Is this normal? and if it is normal can anybody tell me where this other data is coming from?

like image 899
Josh Moore Avatar asked Feb 13 '26 09:02

Josh Moore


1 Answers

This is a very old question but even almost 10 years later, the answer is still the same - it seems that fixtures ignore the schema format and are hard-coded to look for YAML files. Here's the Rake task as of Rails 5.2-stable:

https://github.com/rails/rails/blob/5-2-stable/activerecord/lib/active_record/railties/databases.rake#L198

Line 214 uses Dir["#{fixtures_dir}/**/*.yml"] to find files, so only .yml will be read.

Solutions revolve around loading your SQL fixtures into an otherwise empty database, then dumping them as YAML using the yaml_db gem or something such as that described in this blog post. Since links to blog posts often die quite quickly, I've replicated the source below:

namespace :db do
  desc 'Convert development DB to Rails test fixtures'
  task to_fixtures: :environment do
    TABLES_TO_SKIP = %w[ar_internal_metadata delayed_jobs schema_info schema_migrations].freeze

    begin
      ActiveRecord::Base.establish_connection
      ActiveRecord::Base.connection.tables.each do |table_name|
        next if TABLES_TO_SKIP.include?(table_name)

        conter = '000'
        file_path = "#{Rails.root}/test/fixtures/#{table_name}.yml"
        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
      end
    ensure
      ActiveRecord::Base.connection.close if ActiveRecord::Base.connection
    end
  end
end

The code above was published on July 16, 2017 by Yi Zeng. You'd put this in a file called something like lib/tasks/to_fixtures.rake. I loaded my SQL fixture data into the otherwise empty/clean test-mode database, then ran RAILS_ENV=test bundle exec rake db:to_fixtures. It worked as-is for me under Rails 5.2.3.

like image 75
Andrew Hodgkinson Avatar answered Feb 15 '26 09:02

Andrew Hodgkinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!