forget about the view

Recently I was looking at some of ActiveRecord‘s class level validation
methods and realizing I don’t really use a lot of them. Until I took a look at
#validates_inclusion_of.

Say we got

classEvent<ActiveRecord::BaseTYPES=%w(daily weekly monthly)end

schema

events (id, title, event_type)

view

app/views/events/new.rhtml

<%=form.select:event_type,Event::TYPES,:include_blank=>true%>

So when POST'ing from the form on app/views/events/new.rhtml there’s no chance
I’ll get an event type other than the 3 (or blank) I show in the drop down list.

What if someone did a POST via curl and did

event[title]=title&amp;event[event_type]=asdf

'asdf’ is not one of my Event::TYPES but my Event record is still going to
save. I know this is probably far fetched but we should be building our models
without any notion of the UI, be it browser or not. So we need validations for
everything.

If you enjoyed this post, you might also like:

Want to level up your testing game?
Learn about testing Rails applications and TDD
in our new book
Testing Rails.
The book covers each type of test in depth,
intermediate testing concepts,
and anti-patterns that trip up even intermediate developers.