title: unit testing the unique constraint on domain class
body: <p>I'm using Grails 2.4.1 and having trouble understanding how to properly test a unique constraint on a domain class.</p>
  
  <p>My domain class looks like:
      class Person {</p>
  
  <pre><code>    String name
      static constraints = {
          name( unique: true, blank: false )
      }
  }
  </code></pre>
  
  <p>and my test:</p>
  
  <pre><code>@TestFor(Person)
  @TestMixin(GrailsUnitTestMixin)
  class PersonSpec extends Specification {
  
  void "name should be unique"() {
      given:
      mockForConstraintsTests Person
  
      when:
      def one = new Person( name: 'john' )
  
      then:
      one.save()
  
      when:
      def two = new Person( name: 'john' )
  
      then:
      ! two.validate()
      two.errors.hasFieldErrors( 'name' )
  
  }
  </code></pre>
  
  <p>The second instance is validating despite apparently violating the unique constraint.  Can someone please explain what's going on here and how I should best correct it?</p>
  
  <p>Thanks!</p>
  
  <p>--john</p>