Default columns in fixtures

Posted on January 03, 2008

Ever find yourself writing out the same old column names in fixtures just so your tests will work? Ever wonder if there’s a better way? Well there is!

Fixtures, now with NEW default columns!

All you need to do is bung a method in your test/test_helper.rb file that looks like this:

  def default_columns
    columns = <<END_OF_STRING
    created_at: 1 Jan 2007
    created_by: 1
    updated_at: 1 Jan 2007
    updated_by: 1
    lock_version: 1
  END_OF_STRING     
  end

Now, in each fixture that requires the default columns put this at the top:

<% require "#{RAILS_ROOT}/test/test_helper.rb" %>                    
And then for each fixture bung in this inline code:
one:
  id: 1   
  name: MyString
<%= default_columns %> 

Voila! No more repeating yourself with stupid columns! Hooray!

Note: spacing is important in yaml files – so make sure you put the <%= default_columns %> in an appropriate place