[rspec-users] How can I create a active-record model w/o depending on the database?

David Chelimsky dchelimsky at gmail.com
Mon Sep 24 00:31:56 UTC 2012

On Sun, Sep 23, 2012 at 7:55 PM, S Ahmed <sahmed1020 at gmail.com> wrote:
> I have a class that takes a class that inherits from activerecord as a
> parameter, e.g.:
> class SomeModel < ActiveRecord::Base
> end
> class MyClass
>   attr_accessor :model
>   def initialize(model)
>     @model = model
>   end
> end
> The class MyClass will then iterate over the Models attributes etc.
> Also I will need to know each attributes data type in mysql like: integer,
> boolean, etc.
> So my unit tests shouldnt' rely on the database, but I'm a little confused
> on how I can create stub/mock that will have attributes on it similiar to
> how it would be if I was creating a model and it reading the mysql columns
> as attributes.
> Thoughts on how I can do this w/o actually having to depend on a database
> for my spec tests?

There is a guideline that says "Don't mock types you don't own," which
I've just learned was coined by my colleague at DRW, Joe Walnes [1].

In this case, this guideline suggests that you stub/mock MyClass in
tests for the objects that interact with it, thereby isolating _them_
from the database, but that the tests for MyClass itself are allowed
to interact w/ the database through the AR model. This limits your
dependency on AR to MyClass and its tests, so changes to ActiveRecord
and/or decisions to move to a different database abstraction don't fan
out very far.

Make sense?

Make sense?

More information about the rspec-users mailing list