[rspec-users] Testing attr_accessible (and/or attr_protected)
Iain E. Davis
iain at somethingelectronic.com
Tue Nov 2 12:55:51 EDT 2010
> To me, checking whether the attribute changed is more straight-forward
> than implementing a custom matcher, at least at my current level of
> experience (novice) with rails and rspec.
Okay, so that didn't last very long. Suddenly, I was swimming in very
repetitive code in my _spec files...I could feel my eyes closing from
In light of that experience and the excellent points that Rick made, I
think I'll go hunt down a custom matcher that checks that I actually
set the planned attr_accessible, rather than doing it the way I just
did it! I'll start by looking at the link to Shoulda's matcher,
kindly provided by Evgeniy earlier.
It works the other way, but the repetition was driving me crazy, and
as Rick says:
> It indirectly tests whether or not attr_accessible/attr_protected is in effect by observing the effect on
> one of the methods which are effected by those 'declarative' methods.
I agree...I was at some level sort of aware of that but didn't know
enough (yet) to overcome it. :)
> The second approach is more compatible with that philosophy. I trust that ActiveRecord correctly
> implements protected attributes, what I want to prove is that my code is using them.
Exactly. The way I've begun to think is "...if I add a line of code
to do X, will my test flag a failure if that line is not there?". That
way I'm writing tests that insure that the code _I've_ (or my team
has) written is correct, and not testing Rails/Authlogic/Rspec/etc.
 "Line" is a bit misleading, since I could leave off a _portion_ of
a line in the case of attr_accessible and similar pieces.
More information about the rspec-users