While developing your Rails application you will often use seed files so you have a consistent data set during your development cycle.

I prefer to use JSON files which are stored in the directory /db/seeds.

One of the reasons I’m using JSON over YML is that I have build up a large collection of seeds over the past decades eg for countries, currencies, states and zipcodes and they all are in JSON format, so let’s stick with that.

In your seeds.rb file you can load your files like this

if Country.count == 0
  path = File.join(File.dirname(__FILE__), "./seeds/countries.json")
  records = JSON.parse(File.read(path))
  records.each do |record|
    Country.create!(record)
  end
  puts "countries are seeded"
end

This will load the countries.json file

Testing

To support your functional-, unit and system tests you also need data for testing. By default these are YAML file (with extension.yml) which are stored in the test/fixtures directory.

While in the past i had different fixtures for testing as the seeds I was using for the development, this didn’t make sense, so I wrote a little ruby script which converts all my JSON seed files and converts them to the YAML format and places them in the fixtures folder.

Here’s the code for you to copy, use, adapt to your requirements.

I’ve called the file convert_seeds.rb which you can run in your terminal with the following command:

ruby convert_seeds.rb
gem 'humanize'
require 'json'
require 'humanize'
require 'pathname'

puts "Deleting all files under the test/fixtures directory"
Pathname.new('./test/fixtures/').children.each do |path|
  File.delete(path) if File.exist?(path)
end
puts "Converting all files under the db/seeds directory"
Pathname.new('./db/seeds/').children.each do |path|
  file_name = path.basename.to_s
  new_file_name = file_name.gsub! 'json', 'yml'
  if(!File.directory?(path))
    records = JSON.parse(File.read(path))
    keys = records[0].keys
    #initialize counter for humanize
    counter = 1
    f = File.new('./test/fixtures/'+new_file_name, 'w')
    records.each do |record|
      clean_key = counter.humanize.gsub " ","-"
      f.write(clean_key +":\n")
      keys.each do |k|
        f.write("  "+k+": " + record[k].to_s+"\n")
      end
      counter +=1
    end
    f.close
  end
end

Happy testing 🙂

First published on my medium page https://medium.com/@petervandeput/use-your-json-seed-files-to-testing-in-rails-d708dc80c4a7

Tags

Comments are closed