Pundit rails authorisation with RSpec

Authorisation is always an issue and have to be dealt carefully. Often you start with simple home made statements like user.admin?, etc. For the TEAM ORGA application also came the time to switch from a custom solution to a solid community proofed and backed solution. First you will think about the well known CanCan gem from Ryan Bates.

But I decided to use Pundit from the guys of Elabs. Mainly because of the following reasons I decided to do so:

  • Pundit uses “regular Ruby classes and object oriented design patterns to build a simple, robust and scaleable authorization system”, while CanCan uses a pseudo DSL with a central ability.rb model.
  • Though according to The Ruby Toolbox CanCan is much wider spread, it doesn’t work out of the box with Rails 4 and has - with few commits and many open issues - the signs of an abandoned project.

Thanks to the Pundit readme and two excellent blog posts

the implementation was straight forward. If you use the alternative approach to create Pundit policy specs as outlined in the posts - by scoping to a user context, be aware that you need

  • to enable a custom matcher as described in that section and
  • avoid namespace conflicts, e.g. by choosing a different matcher name or avoid require pundit/rspec in spec_helper.rb !

Furthermore I found a lack of documentation concerning a RSpec examples for pundit_scope, but that can be easily tested like this:

Right, not here. But it doesn’t mean I’m not interested in your feedback. I just prefer to use more busy services ;-) where a wider discussion could incur. So tweet me @netzfisch or if you find an error, fork my blog, correct the post and send me a pull request via GitHub. Thanks for your efforts.
git linux rails vim