haskelltestinghspecacid-state

Testing Acid-State with hspec


i'm a haskell noob and have problems with testing functions with acid-states.This ist my Datastructure

data UserState = UserState { name :: String }
    deriving (Eq, Ord, Read, Show, Data, Typeable)

and this is the function i want to test:

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

This is my test:

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

I have no idea how to model my expected values. UserState{ name = "Mike"} doesn't work


Solution

  • I don't think you can access the database state without querying for it. So you need to add a query to ask for your database state, for example like this:

    getUserState :: Query UserState UserState
    getUserState = ask
    

    Then it is possible to write a test like this :

    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"}