[Ruby] Testing Models in Rails
Aaron Patterson
aaron at tenderlovemaking.com
Fri Jul 27 05:32:31 PDT 2007
On Thu, Jul 26, 2007 at 11:41:33PM -0700, Eric Hodel wrote:
> On Jul 26, 2007, at 10:19, Aaron Patterson wrote:
> > On Thu, Jul 26, 2007 at 01:33:31PM -0700, Laurel Fan wrote:
> >> On 7/26/07, Aaron Patterson <aaron at tenderlovemaking.com> wrote:
> >>> This seems like it should be easy, but I can't figure it out! I
> >>> have a
> >>> model that defines a before_update callback, and I want to assert
> >>> that
> >>> that callback is set. But I don't want to save the object
> >>> because I'm
> >>> trying to avoid hitting the database.
> >>
> >> Why are you trying to avoid hitting the database? I would imagine
> >> that avoiding the database makes it hard to test much of anything.
> >
> > Because hitting the database is expensive. Actually I've found that
> > I can test most of my code without hitting the database. It makes my
> > tests much faster. The problem here is that I don't know how to
> > assert
> > that my callback is defined *without* hitting the database.
> >
> > I trust that the active record callback chain works properly when I
> > call
> > save. I just want to make sure that my callback is in that chain.
>
> I looked into how its stored, and its beyond me. Maybe you can
> figure something out.
>
> User.inheritable_attributes[:before_update] seems to record something
> related to before_update.
This is what I've got so far:
def assert_callback(model_class, callback, method_name, message=nil)
assert(
(vars = model_class\
.instance_variable_get(:@inheritable_attributes)).key?(callback) &&
vars[callback].include?(method_name), message)
end
Its not perfect, but you can say:
assert_callback(Model, :before_save, :something)
--
Aaron Patterson
http://tenderlovemaking.com/
More information about the Ruby
mailing list