module InactiveRecord module Inactivation # Allows an ActiveRecord class to be used without any connection # to the database. # Columns must be specified thought the +attributes+ argument. # Attributes must be a Hash with the column name as the key and # either a value or a symbol representing the column type as its # value. def inactivate!(attributes) self.stubs(:columns).returns(guess_db_columns(attributes)) # Do not save for real! self.class_eval do def transaction yield end def create stubs(:id).returns 1 self.class.finds 1, attributes true end def update true end end end private # Based on http://blog.jayfields.com/2007/03/rails-activerecord-unit-testing-part-ii.html def guess_db_columns(attributes) return [] if attributes.nil? attributes.keys.collect do |attribute| sql_type = case attributes[attribute] when Fixnum then "integer" when Float then "float" when Time then "time" when Date then "date" when String then "string" when Symbol then attributes[attributes].to_s when Object then "boolean" end ActiveRecord::ConnectionAdapters::Column.new(attribute.to_s, nil, sql_type, false) end end end end