Topic: Trouble getting RegEx test to fail

Hi Everyone,

I have a validates_format_of that is giving me trouble. Here's my model:

class UserType < ActiveRecord::Base
  validates_presence_of :position, :user_type
  validates_numericality_of :position
  validates_format_of :user_type, :with => /^\w+$/, :on => :update, :on => :create
  validates_uniqueness_of :position, :user_type
end

I only want to allow word-characters for :user_type, no numbers, punctuation, etc. My test is:
def test_invalid_update
    ut = UserType.find 1
    ut.update_attribute(:user_type, 'Staff User 1')
    assert !ut.valid?
    assert ut.errors.invalid?(:user_type)
  end

But, this is not failing. Can someone please give me a hand? Also, if anyone knows of a good reference for Rails RegExes, I would really appreciate it!

TIA,

Brandon Taylor
Sr. Developer

Dell

Re: Trouble getting RegEx test to fail

update_attribute doesn't validate. If you want a validations to run and really want to do the update, then use update_attributes. I'm not sure I follow your test strategy. Are you testing the validation or the update. If the former, leave out the update_attribute and you're done. If the latter, then you're basically testing ActiveRecord, no?

Re: Trouble getting RegEx test to fail

Hi,

I know validations run during create by default, and you can specify that they also run on update, e.g.

validates_format_of :user_type, :with => /^\w+$/, :on => :update, :on => :create

Am I misunderstanding the "on" option? If I only need to add 'validates_format_of', and not specify when it runs, that's even better.

Thanks,

Last edited by btaylor (2007-10-22 07:37:48)

Brandon Taylor
Sr. Developer

Dell

Re: Trouble getting RegEx test to fail

You don't usually need the on option. But when you do, you really do.

Last edited by cwd (2007-10-22 11:09:50)