Skip to content

Instantly share code, notes, and snippets.

@robrasmussen
Created October 3, 2010 07:50
Show Gist options
  • Save robrasmussen/608375 to your computer and use it in GitHub Desktop.
Save robrasmussen/608375 to your computer and use it in GitHub Desktop.
I've been using variations of this for years to help figure out little problems with ActiveRecord.
require 'rubygems'
require 'active_record'
require 'logger'
ActiveRecord::Base.establish_connection({:adapter => "sqlite3", :database => ":memory:"})
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :people do |t|
t.string :first_name, :last_name
end
create_table :addresses do |t|
t.integer :person_id
t.string :street, :city, :state, :postal_code, :label
end
add_index :addresses, :label
end
class Person < ActiveRecord::Base
has_many :addresses
end
class Address < ActiveRecord::Base
belongs_to :person
scope :labeled, lambda {|name| where(:label => name)}
end
require 'test/unit'
require 'contest'
class PersonTest < ActiveSupport::TestCase
context "Person with a home and school address" do
setup do
@user = Person.create(:first_name => "Jacob", :last_name => "Rasmussen")
@home = @user.addresses.create(:street => "3434 Maple Ave.", :city => "Austin", :state => "TX", :postal_code => "78743", :label => "Home")
@school = @user.addresses.create(:street => "4343 Oak Blvd.", :city => "Austin", :state => "TX", :postal_code => "77878", :label => "School")
end
test "should have a home address" do
assert_equal @home, @user.addresses.labeled("Home").first
end
end
end
@robrasmussen
Copy link
Author

I've been using variations of this for years to help figure out little problems with ActiveRecord.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment