Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Good question. Before the test framework (Test::Unit) runs each test it resets the database to its original state. So before each test you are guaranteed that the DB only has the fixture data and nothing else.</p> <p>This is helpful. You don't want the data from one test still to be there when you start the next test. If it were, the DB state would be inconsistent if you did something like run a test by itself (instead of the whole suite) or run tests in a different order.</p> <p>The solution: you can write a test that specifically verifies that the :username and :email are unique. Before I give an example, I should mention that it looks like you wrote a functional test for this validation. This is tempting because you're verifying the behavior the user will see, but the place to test validation is in the unit tests because validation rules in Rails get pushed down to the models. (To keep validation DRY. You don't have to duplicate your validation rules across a bunch of controllers) </p> <p>So here's one way you could write the unit test:</p> <pre><code>test "should validate unique email" do attributes = { :username =&gt; "newuser", :email =&gt; "newuser@gmail.com", :password =&gt; "secret", :password_confirmation =&gt; "secret" } # create user user1 = User.create(attributes) assert_nil user1.errors.on(:username) assert_nil user1.errors.on(:email) # create another user with the same name and email user2 = User.create(attributes) assert_not_nil user2.errors.on(:username) assert_not_nil user2.errors.on(:email) end </code></pre> <p>For a good article about this, see <a href="http://railstips.org/blog/archives/2009/01/07/test-or-die-validates-uniqueness-of/" rel="nofollow">John Nunemaker's blog post from two years ago</a>. Ignore the accidental HTML tags in his code samples. Nunemaker is an awesome Rails blogger.</p> <p>There are some alternate testing libraries like Shoulda that have built-in functions to validate that your model validates uniqueness. But since you're new to Rails I'd recommend sticking with the default test framework for now. (In fact the folks at 37Signals who invented Rails still use the default too, so that says a lot for it. I also prefer to stick with the default.)</p> <p>By the way, you can format code in a StackOverflow question by indenting it with four spaces.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload