It took me a while to figure out a good way to approach this, so thought I’d share. I’ve been wondering how to best write test code for a Rails plugin that deals with ActiveRecord models, and after trying a few different approaches, I decided to do the thing I should have done in the first place: look at the test code for the plugins in Rails core. The acts_as_tree test code is what I ended up using as a guide for my tests for MultiFieldDate. This approach uses SQLite as an in-memory database, so you do have to have SQLite3 and the sqlite3-ruby gem installed for this to work. Alternatively, this should work with other database engines, but it would probably be a good idea to use table prefixes in those cases to avoid conflicts with existing tables.
Here’s a snippet of the MultiFieldDate test code:
require 'test/unit' require 'rubygems' require 'active_record' $:.unshift File.dirname(__FILE__) + '/../lib' require File.dirname(__FILE__) + '/../init' ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :dbfile => ":memory:") # AR keeps printing annoying schema statements $stdout = StringIO.new def setup_db ActiveRecord::Base.logger ActiveRecord::Schema.define(:version => 1) do create_table :people do |t| t.column :name, :string t.column :birth_date, :date t.column :birth_year, :integer t.column :birth_month, :integer t.column :birth_day, :integer end end end def teardown_db ActiveRecord::Base.connection.tables.each do |table| ActiveRecord::Base.connection.drop_table(table) end end class Person < ActiveRecord::Base multi_field_date :birth, :date_field => 'birth_date', :year_field => 'birth_year', :month_field => 'birth_month', :day_field => 'birth_day' end class PersonTest < Test::Unit::TestCase def setup setup_db end def teardown teardown_db end def test_create_without_birth_date person = Person.new(:name => 'Joe Jones') person.save assert(person.valid?, true) end #... end