Question: In our PostgreSQL-backed Rails project, when running rspec using spork, sometimes we receive the following error:

```
ActiveRecord::StatementInvalid:
   PG::Error: ERROR:  prepared statement "a1" already exists

```

Originally, it occurred only a few times a day, but recently, it has begun happening every 3-4 test runs which slows our development efforts to a crawl.

Is there a way to reset/delete the prepared statements in PostgreSQL somewhere inside of our `spec_helper.rb` file?

Answer: 
After searching the [PostgreSQL docs](http://www.postgresql.org/docs/9.1/static/sql-deallocate.html) and a fair amount of trial and error testing it in different spots inside the `spec_helper.rb`, I finally figured out that I could add the following to delete all existing prepared statements and I have not since seen the error:

```
RSpec.configure do |config|
  # ... other code

  config.after(:suite) do
    ActiveRecord::Base.connection.execute("DEALLOCATE ALL")
  end

  # ... other code
end

```
You can get this if you're doing something like:

```
  class ActiveRecord::Base
    mattr_accessor :shared_connection
    @@shared_connection = nil
    def self.connection
      @@shared_connection || retrieve_connection
    end
  end
  ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection

```

(which was recommended [here](https://gist.github.com/470808)).

If you have that or similar, try removing it.