mherzl
mherzl

Reputation: 6200

How to begin and rollback a transaction with hspec?

I am trying to write a test using hspec involving postgres transaction rollback as with postgresql-simple's begin and rollback commands.

However, applying postgresql-simple's begin and rollback commands appears to cause my 'insert' command not to run and not affect my database at all.

Here is the relevant code.

import qualified Database.PostgreSQL.Simple as PGS
import Test.Hspec (describe, it, SpecWith, hspec, before, after)

testConnInfo :: PGS.ConnectInfo
testConnInfo = PGS.ConnectInfo
  { PGS.connectHost = "localhost"
  , PGS.connectPort = 5432
  , PGS.connectUser = "user"
  , PGS.connectPassword = ""
  , PGS.connectDatabase = "database"
  }

testConnection :: IO PGS.Connection
testConnection = do
  PGS.connect testConnInfo

runSpec :: IO ()
runSpec = do
  conn <- testConnection
  hspec $ test_addTask conn

test_addTask :: PGS.Connection -> SpecWith ()
test_addTask conn = describe "test_addTask" $ do
  it "adding_task_succeeds" $ do
    PGS.begin conn
    addTask conn "taskName"
    print "set breakpoint here"
    PGS.rollback conn
    return ()

I run this in ghci, setting a breakpoint at the "set breakpoint here" line; after the entry should be inserted and before the rollback. While paused at this breakpoint I query the database to see whether the entry has been inserted, and see that no entry appears to be inserted into the database by this code.

When I remove the PGS.begin conn and PGS.rollback conn lines, however, the code does insert the entry into the database.

Why does this code not insert an entry into the database with the 'begin' and 'rollback' lines in place?

How can I write hspec tests which begin and rollback so that my tests do not influence values in the database, and that actually run the commands?

Upvotes: 1

Views: 243

Answers (0)

Related Questions