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

David Chelimsky dchelimsky at gmail.com
Tue May 20 20:25:14 EDT 2008


On May 20, 2008, at 6:59 PM, T K 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?

Are you running with transactional_fixtures = true? If not, I'd  
strongly recommend that you do. Even if you're not using fixtures,  
that setting causes all of your examples to be run in transactions  
that get rolled back after each example. That way, your examples can  
make db changes, expect the right thing, and then the db is restored  
to its previous state.

HTH,
David

>
>
> -T
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users



More information about the rspec-users mailing list