Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in an after hook, PG::InFailedSqlTransaction from Rspec

I was trying to run rspec from a model spec file, but I got this error: "An error occurred in an after hook"

"An error occurred in to after hook PG :: InFailedSqlTransaction: ERROR: current transaction is aborted, commands ignored until end of transaction. occurred at C :/ Ruby193/lib/.../postgresql_adapter: 294 "

I googled this issue, and I found a suggestion to downgrade my 'database_cleaner' to '1.0.1'. I did, but it doesn't work. Does anyone have any idea how to solve this? Thanks in advance!

like image 681
n4d Avatar asked Jan 21 '14 16:01

n4d


1 Answers

This can happen if you execute a bad SQL statement in the scope of a transaction, you rescue the exception from that statement, and then try and execute another SQL statement in the same transaction.

Once one statement in a transaction fails no more statements can be executed in that transaction.

Here's an example:

ActiveRecord::Base.transaction do
  begin
    ActiveRecord::Base.connection.execute "A bad query"
  rescue => ex 
    puts ex.message
  end
  puts User.count
end

User.count raises PG::InFailedSqlTransaction because the previous SQL statement raised ActiveRecord::StatementInvalid and that was swallowed by the rescue.

So I would look for code that rescues in the scope of a transaction and then tries to run additional SQL statements.

like image 114
Scott Jacobsen Avatar answered Nov 05 '22 05:11

Scott Jacobsen