Unit testing IO actions with Hspec

前端 未结 1 1261
情话喂你
情话喂你 2021-01-14 00:55

I have found other questions on similar lines but nothing that answers my question in this particular scenario. Furthermore, there seem to be few resources which succinctly

相关标签:
1条回答
  • 2021-01-14 01:22

    Would this work for you?

    #!/usr/bin/env stack
    -- stack exec --package transformers --package hspec -- ghci
    import Control.Monad.IO.Class
    import Control.Monad.Trans.Identity
    
    import Data.Char
    import Test.Hspec
    
    data Something = Something String deriving (Eq, Show)
    
    class MonadIO m => MonadDB m where
      getSomething :: String -> m Something
      getSomething s = return $ Something (map toUpper s)
    
    instance MonadDB IO
    
    instance MonadIO m => MonadDB (IdentityT m)
    
    getIt :: MonadDB m => m (Int, Something)
    getIt = do
      s@(Something str) <- getSomething "hi"
      return (length str, s)
    
    main :: IO ()
    main = hspec $ do
      describe "Some tests" $ do
        it "test getIt" $ do
          runIdentityT getIt `shouldReturn` (2, Something "HI")
    
        it "test getIt should fail" $ do
          runIdentityT getIt `shouldReturn` (1, Something "HI")
    

    You might also be able to use ReaderT or StateT to "supply" data or a transformation for getSomething to use upon test querying.

    Edit: Example use from within hspec.

    0 讨论(0)
提交回复
热议问题