[rspec-users] Testing attr_accessible (and/or attr_protected)

Wincent Colaiuta win at wincent.com
Tue Nov 2 03:20:07 EDT 2010

On 02/11/2010, at 01:36, Iain E. Davis wrote:

> I've been puzzling over how to test that attr_accessible has been set
> for the correct columns; but the tests I've come up with so far seem
> to fail to fail when I expect. I came across this old message from
> this list:
> http://www.mail-archive.com/rspec-users@rubyforge.org/msg01570.html
> Which seemed like a plausible example, but my attempt (modeled on the
> example) doesn't work:
> describe Article, 'protected attributes' do
>     it 'should deny mass-assignment to the user_id' do
>       lambda { article.update_attributes(:person_id =>  @person.id)
> }.should raise_error
>     end
> end
> The lambda doesn't raise an error, even though the attr_accessible
> doesn't include person_id.
> Where am I stumbling here? Is it my beginner's knowledge of rails, or
> beginner's knowledge of Ruby?

I'm the author of that message you linked to from three years ago. Things have changed quite a bit since then.

Right now, I check for this stuff using a custom matcher:


Which can be used like this:

  article.should_not allow_mass_assignment_of(:person_id => @person.id)


  article.should allow_mass_assignment_of(:person_id => @person.id)

I'm not the only one to have written custom matchers like this though; if you Google (for "rspec custom matcher rails" or "rspec macro rails") you'll probably find a bunch for doing this, and for other stuff (like testing validations, associations etc).


More information about the rspec-users mailing list