[rspec-users] How to write a test for validates_uniqueness_of

Kyle Hargraves philodespotos at gmail.com
Tue May 20 20:23:18 EDT 2008


On Tue, May 20, 2008 at 6:59 PM, T K <tek.katu at gmail.com> wrote:
> Hi,
>
> I have a spec
>
>  it "should have a unique username "
>
> I have a code:
>
>  validates_uniqueness_of :user_name
>
>
> Now, I don't know how to test this code. In order to test this, do I
> need to run `save`?
>
> For example,
>
> @user = User.create(:username => "mike")
> @another = User.create(:username => "mike")
> @another.save.should be_false
>
> This messes up test database. Is there any better way?

I'm not sure what you mean when you say it messes up the test
database, but you can either call :create! for the second creation and
expect an exception:

  lambda { User.create!(:username => 'mike') }.should
raise_error(ActiveRecord::RecordInvalid, /already taken/)

Or you can just call :new and test if it's valid:

  another = User.new(:username => 'mike')
  another.should_not be_valid
  another.should have_at_least(1).errors_on(:username) # or similar

I tend to go with the second option, but see the first used pretty
often as well.

k


More information about the rspec-users mailing list