Wednesday, June 26, 2013

Silence is NOT golden...

Here's a sneaky little routing gotcha.  Let's say you're TDD'ing a new feature and your test requires a 'new' action. Following best practice, you start by saying
resources :accounts, only: [:new]
instead of
resources :accounts
Before we get to the gotcha, why would I say 'best practice' is to avoid the complete definition? Well... remember one of the core principles of TDD:
Write ONLY enough code to get the test to pass.
This means that adding only a single action is all I need do to get the test to pass, so that's all I add (even though I actually write more code in that case). This idea certainly isn't new to me; for example, check out the Thoughtbot TDD class if you're interested in learning more: great resource!

On a broader scale, assuming you've got this whole feature written, you still want to avoid adding any unused actions. If you use every RESTful action except for :delete, then you don't want to allow the delete action to exist, as it offers one more opportunity for the bad guys to attack your site.

Back to the gotcha. Let's say that you code the above example, but - oops - you make a typo and actually code:
resources :accounts, only: [:newt]
Guess what - this error is silently ignored. No route is generated and you don't get an error message. In fact, the only: and except: options just ignore anything that isn't on the list of RESTful actions (index, create, new, update, edit, show, destroy) and give no warning.

It's easy to overlook this as we're used to having Rails give us helpful error messages if we code something incorrectly. Not so in this case.

No comments:

Post a Comment