Tuesday, July 3, 2012

Testing Rails controller security with RSpec shared examples

Like most developers I'm pretty paranoid about security. For Rails apps, although I don't normally write many a lot of controller tests (because my controllers are always very thin, and I'm usually able to cover their behavior using the style of integration testing I favor), I always make sure to test security functions. I always write tests to ensure no user should be able to view or alter another user's data. Controller tests are the only way to directly test the update, create, and delete actions.

Recently I extracted this type of test into an RSpec shared example and placed it into my power tools gem so I could DRY these tests up. It's been working awesomely. Here's an example:



The code exercises all seven of the standard Rails resource actions if your controller implements them. To see the shared example, check out the power tools gem.

No comments: