用hspec测试酸状态

时间:2017-02-22 20:23:03

标签: haskell testing hspec acid-state

我是一个haskell noob,并且在使用酸状态测试函数方面存在问题。这是我的数据结构

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"}不起作用

1 个答案:

答案 0 :(得分:1)

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

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