Testing IO and Effects in Haskell: MTL, ReaderT, and Effect Systems

Testing IO and Effects in Haskell: MTL, ReaderT, and Effect Systems

Testing Haskell code with IO effects—database calls, HTTP requests, time, randomness—requires separating what your code does from how it does it. The classic techniques are MTL-style typeclasses, the ReaderT pattern, and effect systems (polysemy, effectful). This guide covers each with runnable examples.

The Problem: IO Makes Testing Hard

-- Hard to test: directly uses IO
saveUser :: User -> IO UserId
saveUser user = do
  conn <- getDbConnection
  result <- execute conn "INSERT INTO users ..." user
  return (lastInsertId result)

To test saveUser, you need a real database. Instead, abstract the effect:

Approach 1: MTL-Style Typeclasses

-- Define capability as a typeclass
class Monad m => MonadUserRepo m where
  saveUser    :: User -> m UserId
  fetchUser   :: UserId -> m (Maybe User)
  deleteUser  :: UserId -> m Bool

-- Production implementation
instance MonadUserRepo IO where
  saveUser user = do
    conn <- getDbConnection
    execute conn "INSERT INTO users VALUES (?,?,?)" user
    
  fetchUser uid = do
    conn <- getDbConnection
    query conn "SELECT * FROM users WHERE id = ?" (Only uid)

-- Business logic uses the typeclass — testable!
createUserWithProfile
  :: (MonadUserRepo m, MonadProfileRepo m, MonadTime m)
  => NewUserRequest
  -> m (Either String UserId)
createUserWithProfile req = do
  case validateRequest req of
    Left err -> return (Left err)
    Right user -> do
      now <- getCurrentTime
      uid <- saveUser user { createdAt = now }
      saveProfile uid (defaultProfile req)
      return (Right uid)

Test Double via State Monad

import Control.Monad.State

data MockRepoState = MockRepoState
  { storedUsers    :: Map UserId User
  , nextUserId     :: UserId
  } deriving (Show)

initialState :: MockRepoState
initialState = MockRepoState mempty 1

newtype MockApp a = MockApp
  { runMockApp :: StateT MockRepoState IO a
  } deriving (Functor, Applicative, Monad, MonadIO, MonadState MockRepoState)

instance MonadUserRepo MockApp where
  saveUser user = do
    uid <- gets nextUserId
    modify $ \s -> s
      { storedUsers = Map.insert uid user (storedUsers s)
      , nextUserId  = uid + 1
      }
    return uid

  fetchUser uid = gets (Map.lookup uid . storedUsers)

  deleteUser uid = do
    exists <- gets (Map.member uid . storedUsers)
    when exists $ modify $ \s -> s
      { storedUsers = Map.delete uid (storedUsers s) }
    return exists

-- Test
testCreateUser :: IO ()
testCreateUser = hspec $ do
  describe "createUserWithProfile" $ do
    it "saves user and returns ID" $ do
      let request = NewUserRequest "Alice" "alice@example.com"
      
      (result, finalState) <- runStateT
        (runMockApp (createUserWithProfile request))
        initialState
      
      result `shouldBe` Right 1
      Map.size (storedUsers finalState) `shouldBe` 1

    it "returns Left for invalid email" $ do
      let request = NewUserRequest "Alice" "not-an-email"
      
      (result, finalState) <- runStateT
        (runMockApp (createUserWithProfile request))
        initialState
      
      result `shouldSatisfy` isLeft
      Map.size (storedUsers finalState) `shouldBe` 0  -- Nothing saved

Approach 2: ReaderT Pattern

Instead of typeclasses, thread a record of functions through a ReaderT:

data Env = Env
  { _saveUser    :: User -> IO UserId
  , _fetchUser   :: UserId -> IO (Maybe User)
  , _getCurrentTime :: IO UTCTime
  , _logMessage  :: String -> IO ()
  }

newtype App a = App { runApp :: ReaderT Env IO a }
  deriving (Functor, Applicative, Monad, MonadIO, MonadReader Env)

-- Smart constructors
saveUserApp :: User -> App UserId
saveUserApp user = App $ do
  f <- asks _saveUser
  liftIO (f user)

getCurrentTimeApp :: App UTCTime
getCurrentTimeApp = App $ asks _getCurrentTime >>= liftIO

-- Business logic
createUser :: NewUserRequest -> App (Either String UserId)
createUser req = case validate req of
  Left err -> return (Left err)
  Right user -> do
    now <- getCurrentTimeApp
    uid <- saveUserApp user { createdAt = now }
    return (Right uid)

Test Environment

testEnv :: IORef (Map UserId User) -> IORef UserId -> Env
testEnv usersRef nextIdRef = Env
  { _saveUser = \user -> do
      uid <- readIORef nextIdRef
      modifyIORef usersRef (Map.insert uid user)
      modifyIORef nextIdRef (+1)
      return uid
  
  , _fetchUser = \uid ->
      Map.lookup uid <$> readIORef usersRef
  
  , _getCurrentTime =
      return (UTCTime (fromGregorian 2024 1 15) 0)  -- Fixed time
  
  , _logMessage = \_ -> return ()  -- Discard logs in tests
  }

withTestEnv :: (Env -> IO a) -> IO a
withTestEnv action = do
  usersRef <- newIORef Map.empty
  nextIdRef <- newIORef 1
  action (testEnv usersRef nextIdRef)

-- Test
spec :: Spec
spec = describe "createUser" $ do
  it "creates user with current timestamp" $
    withTestEnv $ \env -> do
      result <- runReaderT (runApp (createUser validRequest)) env
      
      result `shouldBe` Right 1
      
      users <- readIORef (usersRef env)  -- Inspect state
      let user = Map.lookup 1 users
      fmap createdAt user `shouldBe`
        Just (UTCTime (fromGregorian 2024 1 15) 0)

Approach 3: Effect Systems (Polysemy)

For larger codebases, effect systems provide better composability:

{-# LANGUAGE TemplateHaskell #-}
import Polysemy
import Polysemy.State

-- Define effects as GADTs
data UserRepo m a where
  SaveUser    :: User -> UserRepo m UserId
  FetchUser   :: UserId -> UserRepo m (Maybe User)
  DeleteUser  :: UserId -> UserRepo m Bool

makeSem ''UserRepo  -- Generates saveUser, fetchUser, deleteUser

data Clock m a where
  GetCurrentTime :: Clock m UTCTime

makeSem ''Clock

-- Business logic
createUser
  :: Members '[UserRepo, Clock, Error String] r
  => NewUserRequest
  -> Sem r UserId
createUser req = do
  case validate req of
    Left err -> throw err
    Right user -> do
      now <- getCurrentTime
      saveUser user { createdAt = now }

Production Interpreter

runUserRepoIO :: Member (Embed IO) r => Sem (UserRepo : r) a -> Sem r a
runUserRepoIO = interpret $ \case
  SaveUser user -> embed $ do
    conn <- getDbConnection
    execute conn "INSERT INTO users ..." user
  FetchUser uid -> embed $ do
    conn <- getDbConnection
    listToMaybe <$> query conn "SELECT * FROM users WHERE id = ?" (Only uid)
  DeleteUser uid -> embed $ do
    conn <- getDbConnection
    (> 0) <$> execute conn "DELETE FROM users WHERE id = ?" (Only uid)

Test Interpreter

runUserRepoTest
  :: Map UserId User
  -> Sem (UserRepo : r) a
  -> Sem r (Map UserId User, a)
runUserRepoTest initialStore =
  runState initialStore . reinterpret $ \case
    SaveUser user -> do
      store <- get
      let uid = fromMaybe 1 (fmap (+1) $ fst <$> Map.lookupMax store)
      put (Map.insert uid user store)
      return uid
    FetchUser uid -> gets (Map.lookup uid)
    DeleteUser uid -> do
      exists <- gets (Map.member uid)
      when exists $ modify (Map.delete uid)
      return exists

runClockTest :: UTCTime -> Sem (Clock : r) a -> Sem r a
runClockTest fixedTime = interpret $ \case
  GetCurrentTime -> return fixedTime

-- Test
spec :: Spec
spec = describe "createUser" $ do
  it "saves with fixed timestamp" $ do
    let fixedTime = UTCTime (fromGregorian 2024 1 15) 0
    let request = NewUserRequest "Alice" "alice@example.com"
    
    result <- runM
      . runError @String
      . runClockTest fixedTime
      . fmap snd
      . runUserRepoTest Map.empty
      $ createUser request
    
    result `shouldSatisfy` isRight

Testing Time-Dependent Code

Control time in tests to avoid flakiness:

class Monad m => MonadTime m where
  getCurrentTime :: m UTCTime

-- Test instance with controllable time
newtype TestTime a = TestTime { runTestTime :: ReaderT UTCTime IO a }
  deriving (Functor, Applicative, Monad, MonadIO, MonadReader UTCTime)

instance MonadTime TestTime where
  getCurrentTime = ask

withFixedTime :: UTCTime -> TestTime a -> IO a
withFixedTime t action = runReaderT (runTestTime action) t

-- Test
it "token expires after 1 hour" $ do
  let issueTime = UTCTime (fromGregorian 2024 1 15) (3600 * 10)  -- 10:00 AM
  let checkTime = UTCTime (fromGregorian 2024 1 15) (3600 * 11 + 1)  -- 11:00:01 AM

  token <- withFixedTime issueTime $ issueToken "user-1"
  
  result <- withFixedTime checkTime $ validateToken token
  result `shouldBe` Left TokenExpired

Conclusion

Testable Haskell effectful code separates the description of an effect from its interpretation. MTL typeclasses work well for small-to-medium codebases. The ReaderT pattern is simple and explicit. Effect systems (polysemy, effectful) scale to large codebases with many orthogonal effects. In all cases, the test technique is the same: provide a pure interpreter that collects effects into inspectable data structures, then assert on those structures.

Read more

Start now free