[rspec-users] RSpec - Testing ActiveRecord addins

Ben Mabey ben at benmabey.com
Thu Jan 29 17:06:08 EST 2009

James B. Byrne wrote:
> I wish to test a small library that I have written.  The module
> resides in a file in ./lib.  It is loaded in the application via a a
> file in ./config/initializers that contains the following code:
>> require 'hll_audit_stamps'
>> ActiveRecord::Base
>>  include ActiveRecord::HLLAuditStamps
>> end
> My questions are really procedural in nature.  What do I put at the
> top of my spec file to load an ActiveRecord instance containing the
> custom module? Or, do I put the code given above into
> spec_helper.rb?
> I am really only interested in the actions of the module so I would
> like to create a test model instance (Mytable) inside the spec
> rather than create a dummy model in app/models.  How do you do this
> without connecting to an underlying database?  I am unfamiliar with
> mocks, although this seems to be the case for one.  Nonetheless, am
> am uncertain how a mock would inherit the necessary characteristics
> from the module that I am testing?
> I would appreciate guidance here.
> Sincerely,
Hi James,
 From the looks of it you may want to move your module into a plugin and 
then have it's own set of specs.  Doing this may make your life easier 
in running specs in the fashion you are wanting to.  In the past I have 
done just this and have used the in-memory sqlite3 adapter with some 
dummy AR classes, just as you have explained.  In your plugin's 
spec_helper put something like this:

ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :dbfile 
=> ":memory:")

def setup_db
  ActiveRecord::Schema.define(:version => 1) do
    create_table :vehicles do |t|
      t.string :type, :name
      t.integer :dealership_id
    create_table :dealerships do |t|
      t.string :name

def teardown_db
  ActiveRecord::Base.connection.tables.each do |table|


class Vehicle < ActiveRecord::Base

class Dealership < ActiveRecord::Base

You can then use the dummy AR classes in your specs with an in-memory DB. 

I hope that helps,


More information about the rspec-users mailing list