T_K
May 21, 2008, 2:00am
1
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?
-T
T_K
May 21, 2008, 2:25am
2
On May 20, 2008, at 6:59 PM, T K wrote:
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_K
May 21, 2008, 2:23am
3
On Tue, May 20, 2008 at 6:59 PM, T K [email protected] wrote:
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
T_K
May 21, 2008, 5:33am
5
On 5/20/08, Maurício Linhares [email protected] wrote:
This plugin does it → Google Code Archive - Long-term storage for Google Code Project Hosting.
But it’s throwing a “forbidden” error right now.
Sorry, moved the plugin over to GitHub
(GitHub - joshknowles/rspec-on-rails-matchers: A collection of RSpec matchers to be used with the Ruby on Rails project ).
Finally finding some time to integrate the many wonderful patches from
folks over the last month or so.
–
Josh K.
phone: 509-979-1593
email: [email protected]
web: http://joshknowles.com
T_K
May 21, 2008, 2:29am
6