SameShirtEveryDay.com

Personal blog of the one called Alex Gorbatchev, from Toronto, Canada.

Use fixtures for placeholder data

Posted on May 13th, 2007 by Alex Gorbatchev. In Rails, Testing. No comments yet...

Rails allows you to create data fixtures which can contain test data which is used during unit tests and gets loaded into a _test database.

It’s possible to load that data into your _development database so that you can use the same data while looking at your site in the browser. This can be achieved using a rake command.

rake db:fixtures:load

Maintaining your fixtures could become realy tiresome, especially in text mode. So, there’s a way to generate YAML fixtures from the data. I use the following method to so.

def table_to_yaml(table_name, key_column = 'name')
  return nil if table_name.nil?

  list = ActiveRecord::Base.connection.select_all(
        "SELECT * FROM #{table_name.to_s} ORDER BY id ASC"
  )

  result = ""

  list.each do |record|
    name = record[key_column.to_s].to_permalink
    name = "_#{name}" if name =~ /^[^a-zA-Z]/
    hash = {}
    hash[name] = record
    result < < hash.to_yaml().gsub(/^---s*$/m, '')
  end

  return result
end

key_column is a column name which will be used to name your records in YAML.

This doesn’t generate the actual files, but you can grab the output and save it in your fixtures.

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet, be the first one!

Leave a Reply

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> , rel="nofollow" in use - no link dropping, no keywords or domains as names; do not spam, and do not advertise!

home
Subscribe to this blog Follow me on Twitter My bookmarks on Delicious My photography on Flickr