Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

mocking ActiveRecord (See related posts)

A search didn't turn anything up, so I tried this:

ActiveRecord::Base.class_eval do
  alias_method :save, :valid?
  def self.columns() @columns ||= []; end
  
  def self.column(name, sql_type = nil, default = nil, null = true)
    columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type, null)
  end
end


The mock model:

class User < ActiveRecord::Base
  validates_presence_of :login
  column :id,       :integer
  column :login,    :string
  column :password, :string
  column :active,   :boolean, true
end


This should provide a quick way to test validations and things like that...

Comments on this post

floehopper posts on Aug 26, 2006 at 14:33
Very neat.

Have you had a look at Mocha which allows you to mock/stub methods on concrete objects and classes. So you can mock the ActiveRecord methods like create, save, destroy.

You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts