[rspec-users] Specing based on user roles

Pat Maddox pergesu at gmail.com
Thu Nov 6 16:52:42 EST 2008

Fernando Perez <lists at ruby-forum.com> writes:

>> And why wouldn't you want to test that?
> I want to test for it, it's just that I don't want to copy/paste spec 
> like an idiot.
>> def for_roles *roles
>>   roles.each do |role|
>>     before(:each) { login_as role }
>>     yield
>>   end
>> end
>> describe OrdersController do
>>   describe "GET index" do
>>     for_roles :admin, :sysadmin do |role|
>>       it "..." do ... end
>>     end
>>     for_roles :sysadmin do |role|
>>       it "..." do ... end
>>     end
>>   end
>> This scheme makes it easy when we decide to remove a privilege from
>> admin but keep it in sysadmin. Just move that example (it "...") to
>> the other for_roles block.
>> WDYT?
> I like your idea very much, very clean, readable and maintainable.
> And thank you Mark, I will also use your idea to factor out 
> commonalities in my specs.

A lot of the time when I'm faced with this issue - there's a number of
roles, each with a set of privileges - I find it easier to focus on the
privileges rather than the roles themselves.  This means creating
domain-specific methods on the user object.  #can_edit_orders?,
#can_publish?, etc.  Now when I'm specing at the controller level, I
only have to deal with two cases - when the user has the privilege, and
when he doesn't.  Then we write examples for all of the different roles
at the model level.  No duplication, no fuss.

One thing I've noticed is that when I'm writing controller specs and
there seems to be too much duplication, I can usually eliminate it by
pushing some logic down the stack.  In fancier terms, it means I need to
encapsulate a domain concept that I've missed up to that point.


More information about the rspec-users mailing list