使用 hspec 测试酸状态

Testing Acid-State with hspec

我是一个 haskell 菜鸟,在使用 acid-states.This ist my Datastructure

测试函数时遇到问题
data UserState = UserState { name :: String }
    deriving (Eq, Ord, Read, Show, Data, Typeable)

这是我要测试的功能:

setName :: String -> Update UserState String                  
setName n =      
    do c@UserState{..} <- get 
       let newName = n 
       put $ c { name = newName } 
       return newName
$(makeAcidic ''UserState ['setName ])

这是我的测试:

spec :: Spec
spec = do
  describe "test" $
    it "test" $ do
            setName "Mike" `shouldBe` UserState{ name = "Mike"}

我不知道如何为我的期望值建模。 UserState{ name = "Mike"} 无效

我认为您无法在不查询的情况下访问数据库状态。 所以你需要添加一个查询来询问你的数据库状态,例如:

getUserState :: Query UserState UserState
getUserState = ask

那么可以这样写一个测试:

withDatabaseConnection :: (AcidState UserState -> IO ()) -> IO ()
withDatabaseConnection = 
    bracket (openLocalState UserState{name = "initial name"}) 
            closeAcidState

spec :: Spec
spec = do
    around withDatabaseConnection $ do
        describe "test" $
            it "test" $ \c -> do
                _ <- update c (SetName "Mike") 
                userState <- query c GetUserState
                userState `shouldBe` UserState{ name = "Mike"}