[rspec-users] Example for attr_accessible?

Steve vertebrate at gmail.com
Tue Oct 16 11:55:40 EDT 2007


On Tue, 16 Oct 2007 10:39:32 +0200, Wincent Colaiuta wrote:

> Yes, I spec this kind of thing.
> 
>    describe User, 'accessible attributes' do
>      it 'should allow mass-assignment to the login name' do
>        lambda { new_user.update_attributes(:login_name =>  
> String.random) }.should_not raise_error
>      end
>      # many other examples here, one for each accessible attribute  
> that I care about
>    end
> 
>    describe User, 'protected attributes' do
>      it 'should deny mass-assignment to the passphrase hash' do
>        lambda { new_user.update_attributes(:passphrase_hash =>  
> String.random) }.should raise_error
>      end
>      # many other examples here, one for each protected attribute  
> that I care about
>    end
> 
> I do it this way because:
> 
> 1. I am most interested in the *behaviour*; does this let me mass- 
> assign to this attribute (or not)?
> 
> 2. I don't want my specs to depend on internal knowledge of the Rails  
> attribute protection/access implementation.
> 
> The style of spec shown above seems the best way to me of both  
> documenting the desired behaviour and confirming that it exists; I  
> don't view these as tests of Rails' internals, but as tests that I've  
> used attr_accessible and attr_protected correctly. I tried other ways  
> in the past, but this is the one I like best.
> 
> Another thing to note that helps the readability of the specs: the  
> new_user and String.random methods are provided by FixtureReplacement  
> (<http://replacefixtures.rubyforge.org/>). Note that by default  
> FixtureReplacement used mass-assignment under the covers, so it can't  
> be used with protected attributes, but I've sent a patch in to the  
> maintainer which changes that:

I'm all for avoiding rails internal behavior, but attr_accessible deals on a share least model. If you can verify that only
attrs x, y, z are accessible, you know that any other field
that rails can come up with, or you add later is covered.

I just saw FixtureReplacement the other day, and plan on giving it a go.
Looks like it does a bunch of what I already do manually.



More information about the rspec-users mailing list