1

Problem trying to unit test routes. Scotty, Persistent, and Hspec-WAI.

Unlike Yesod or Spock, Scotty doesn't have a nice place to store database handlers. I've got it working by having one massive "do" that starts up the database, keeps the database pool as a local variable, then uses that variable.

app :: IO ()
app = do
    -- allocate_database  $ \pool
      -- scotty 8080 $do 
      --     handleSomeRoute pool

However, Hspec-WAI wants it in the IO Application form.

scottyApp :: ScottyM () -> IO Application

Is there a sane way to inject the DB connection pool into a scottyApp ?

Chad Brewbaker
  • 2,523
  • 2
  • 19
  • 26

1 Answers1

4

Here's how you can do it. Basically you open the database before you make the hspec call:

{-# LANGUAGE OverloadedStrings #-}

import           Test.Hspec
import           Test.Hspec.Wai
import           Network.Wai (Application)
import qualified Web.Scotty as S

allocate_db :: (Int -> IO a) -> IO a
allocate_db = undefined

handleSomeRoute :: Int -> S.ScottyM ()
handleSomeRoute = undefined

main2 :: IO ()
main2 = allocate_db $ \pool -> do
  let app' = handleSomeRoute pool
  hspec $ with (S.scottyApp app') $ do
            describe "GET /" $ do
              it "responds with 200" $ do
                get "/" `shouldRespondWith` 200
ErikR
  • 51,541
  • 9
  • 73
  • 124