introduce a fake AR adapter for mocking database return values

This commit is contained in:
Aaron Patterson 2011-02-04 13:34:41 -08:00
parent adbae9aab8
commit df07760486
2 changed files with 43 additions and 5 deletions

@ -0,0 +1,36 @@
module ActiveRecord
class Base
def self.fake_connection(config)
ConnectionAdapters::FakeAdapter.new nil, logger
end
end
module ConnectionAdapters
class FakeAdapter < AbstractAdapter
attr_accessor :tables, :primary_keys
def initialize(connection, logger)
super
@tables = []
@primary_keys = {}
@columns = Hash.new { |h,k| h[k] = [] }
end
def primary_key(table)
@primary_keys[table]
end
def merge_column(table_name, name, sql_type = nil, options = {})
@columns[table_name] << ActiveRecord::ConnectionAdapters::Column.new(
name.to_s,
options[:default],
sql_type.to_s,
options[:null])
end
def columns(table_name, message)
@columns[table_name]
end
end
end
end

@ -1,12 +1,14 @@
class Contact < ActiveRecord::Base
def self.columns
@columns
end
establish_connection(:adapter => 'fake')
connection.tables = ['contacts']
connection.primary_keys = {
'contacts' => 'id'
}
# mock out self.columns so no pesky db is needed for these tests
def self.column(name, sql_type = nil, options = {})
@columns ||= []
@columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, options[:default], sql_type.to_s, options[:null])
connection.merge_column('contacts', name, sql_type, options)
end
column :name, :string