title: RSpec expect HTTP error status
body: <p>In this example, I create a project, then send a post to create another project with the same name. As it should, it raises ActiveRecord::RecordNotUnique. I also want to check that it returns a 409 HTTP status, but since it raises the error, it automatically fails the test. How can I check that it returns a 409?</p>
  
  <pre><code>require 'rails_helper'
  
  RSpec.describe 'Project Requests', type: :request do
  
    it 'Refuses duplicate projects' do
      project_1 = FactoryGirl.create(:project)
      post '/projects', name: project_1.name
      expect(response.status).to eq(409)
    end
  end
  </code></pre>
  
  <p>Here's the RSpec output:</p>
  
  <pre><code>Failures:
  
    1) Project Requests Refuses duplicate projects
       Failure/Error: post '/projects', name: project_1.name
       ActiveRecord::RecordNotUnique:
         PG::UniqueViolation: ERROR:  duplicate key value violates     unique constraint "index_projects_on_name"
         DETAIL:  Key (name)=(Dr. Brain) already exists.
         : INSERT INTO "projects" ("name", "created_at",     "updated_at") VALUES ($1, $2, $3) RETURNING "id" 
  </code></pre>
  
  <p>Below is my second approach. I expect the error, and that part works fine, but I can't check the status because it never gets to that line. (Notice how the puts command doesn't output anything in the RSpec results.)</p>
  
  <pre><code># spec/requests/project_request_spec.rb
  require 'rails_helper'
  
  RSpec.describe 'Project Requests', type: :request do
  
    it 'Refuses duplicate projects' do
      project_1 = FactoryGirl.create(:project)
      expect {
        response = post '/projects', name: project_1.name
        puts("This code is never executed because the line above fails")
        expect(response.status).to eq(409)
      }.to raise_error(ActiveRecord::RecordNotUnique)
    end
  
  end
  </code></pre>
  
  <p>Here's my RSpec output:</p>
  
  <pre><code>Project Requests
  Puts should output text to the console.
    Refuses duplicate projects
  </code></pre>
  
  <p>That will pass no matter what error code it returns, so even though the test passes, it doesn't test what it's supposed to.</p>