title: Testing PG Database Constraints with RSpec
body: <p>I'm trying to test PG database constraints in a rails 4 using RSpec, and I'm not sure how to set it up.</p>
  
  <p>My thought was to do something like this:</p>
  
  <pre><code>before do
    @subscriber = Marketing::Subscriber.new(email: "subscriber@example.com")
  end
  
  describe "when email address is already taken" do
    before do
      subscriber_with_same_email = @subscriber.dup
      subscriber_with_same_email.email = @subscriber.email.upcase
      subscriber_with_same_email.save
    end
  
    it "should raise db error when validation is skipped" do
      expect(@subscriber.save!(validate: false)).to raise_error
    end
  end
  </code></pre>
  
  <p>When I run this, it does in generate an error:</p>
  
  <pre><code>PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint
  </code></pre>
  
  <p>However, the test still fails.</p>
  
  <p>Is there a proper syntax to get the test to pass?</p>