Scotty with Persistent和Hspec-wai

时间:2016-05-14 13:11:57

标签: haskell yesod persistent scotty hspec

尝试单元测试路线时出现问题。 Scotty,Persistent和Hspec-WAI。

与Yesod或Spock不同,Scotty没有一个存放数据库处理程序的好地方。我有一个大的“do”启动数据库,将数据库池保存为局部变量,然后使用该变量。

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

但是,Hspec-WAI希望它在IO申请表中。

scottyApp :: ScottyM () -> IO Application

是否有将数据库连接池注入scottyApp的明智方法?

1 个答案:

答案 0 :(得分:3)

以下是如何做到的。基本上,在进行hspec调用之前打开数据库:

{-# 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