Haskell Testing with HSpec: BDD-Style Testing for Functional Code
HSpec is the most popular testing framework for Haskell, bringing a BDD-style describe/it syntax to purely functional code. This guide covers HSpec from basic setup through advanced patterns including custom matchers, shared fixtures, and exception testing.
Setup
Add to package.yaml (hpack) or *.cabal:
# package.yaml
tests:
my-app-test:
main: Spec.hs
source-dirs: test
dependencies:
- my-app
- hspec
- hspec-discover
- QuickCheckWith hspec-discover, create test/Spec.hs:
{-# OPTIONS_GHC -F -pgmF hspec-discover #-}This auto-discovers all *Spec.hs files in your test directory.
Basic HSpec Tests
-- test/Data/UserSpec.hs
module Data.UserSpec (spec) where
import Test.Hspec
import Data.User
spec :: Spec
spec = do
describe "User" $ do
describe "validateEmail" $ do
it "accepts valid email addresses" $ do
validateEmail "alice@example.com" `shouldBe` Right "alice@example.com"
validateEmail "bob+tag@mail.co.uk" `shouldBe` Right "bob+tag@mail.co.uk"
it "rejects emails without @ symbol" $ do
validateEmail "notanemail" `shouldBe` Left "Email must contain @"
it "rejects empty string" $ do
validateEmail "" `shouldBe` Left "Email cannot be empty"
describe "fullName" $ do
it "concatenates first and last name" $ do
let user = User { firstName = "Alice", lastName = "Smith" }
fullName user `shouldBe` "Alice Smith"
it "handles single-name users" $ do
let user = User { firstName = "Cher", lastName = "" }
fullName user `shouldBe` "Cher"Matchers
HSpec provides expressive matchers:
spec :: Spec
spec = describe "Matchers" $ do
it "equality" $ 2 + 2 `shouldBe` 4
it "inequality" $ "hello" `shouldNotBe` "world"
it "satisfy a predicate" $ 42 `shouldSatisfy` even
it "contain an element" $ [1,2,3] `shouldContain` [2,3]
it "start with a prefix" $ "hello world" `shouldStartWith` "hello"
it "end with a suffix" $ "hello world" `shouldEndWith` "world"
it "match a predicate on all elements" $
[2,4,6,8] `shouldSatisfy` all even
it "return Nothing" $ do
let result = lookup "missing" [("key", "val")]
result `shouldBe` Nothing
it "return Just" $ do
let result = lookup "key" [("key", "value")]
result `shouldBe` Just "value"Exception Testing
import Control.Exception (evaluate, ErrorCall(..))
spec :: Spec
spec = describe "safeDiv" $ do
it "divides two numbers" $ do
safeDiv 10 2 `shouldBe` 5
it "throws on division by zero" $ do
evaluate (safeDiv 10 0) `shouldThrow` anyArithException
it "throws a specific error message" $ do
evaluate (unsafeHead []) `shouldThrow`
(== ErrorCall "empty list")
it "does NOT throw for valid input" $ do
evaluate (safeDiv 10 2) `shouldNotThrow` anyExceptionShared Setup with before and around
module Database.UserRepositorySpec (spec) where
import Test.Hspec
import Database.UserRepository
import Database.TestHelpers (withTestDatabase, TestDB)
spec :: Spec
spec = around withTestDatabase $ do
describe "UserRepository" $ do
describe "insert" $ do
it "persists a user to the database" $ \db -> do
let user = NewUser "Alice" "alice@example.com"
userId <- insertUser db user
fetched <- fetchUser db userId
fmap userName fetched `shouldBe` Just "Alice"
it "generates a unique ID for each user" $ \db -> do
id1 <- insertUser db (NewUser "Alice" "a@a.com")
id2 <- insertUser db (NewUser "Bob" "b@b.com")
id1 `shouldNotBe` id2
describe "fetchByEmail" $ do
it "returns the correct user" $ \db -> do
insertUser db (NewUser "Alice" "alice@example.com")
result <- fetchByEmail db "alice@example.com"
fmap userName result `shouldBe` Just "Alice"
it "returns Nothing for unknown email" $ \db -> do
result <- fetchByEmail db "unknown@example.com"
result `shouldBe` Nothing-- test/Database/TestHelpers.hs
module Database.TestHelpers (withTestDatabase) where
import Test.Hspec (ActionWith)
import Database.PostgreSQL.Simple
import Database.UserRepository (TestDB)
withTestDatabase :: ActionWith TestDB
withTestDatabase action = do
conn <- connectPostgreSQL "host=localhost dbname=test_db"
withTransaction conn $ do
action (TestDB conn)
-- rollback at end — transaction never commitsbeforeAll for Expensive Setup
spec :: Spec
spec = do
beforeAll setupExpensiveResource $ do
describe "operations on shared resource" $ do
it "first test" $ \resource -> do
-- resource set up once for all tests in this block
useResource resource `shouldBe` "expected"
it "second test" $ \resource -> do
readResource resource `shouldBe` 42
setupExpensiveResource :: IO ExpensiveResource
setupExpensiveResource = do
putStrLn "Setting up expensive resource (runs once)"
initializeResourcePending Tests
Mark not-yet-implemented tests as pending:
spec :: Spec
spec = describe "PaymentProcessor" $ do
it "charges credit card successfully" $ do
pending -- Not implemented yet
it "handles declined card" $ do
pendingWith "Awaiting payment gateway mock"
it "processes refunds" $ do
-- Implemented
processRefund "txn-123" `shouldReturn` Right ()Focused Tests
Run a subset of tests during development:
spec :: Spec
spec = do
fdescribe "work in progress" $ do -- Only this block runs
fit "specific test I'm working on" $ do
pending
describe "other tests" $ do -- These are skipped with fdescribe
it "not run" $ 1 `shouldBe` 1Remove f prefix before committing — fdescribe/fit should never be in CI.
Custom Matchers
-- test/Helpers/Matchers.hs
module Helpers.Matchers where
import Test.Hspec
-- Custom matcher for Either
shouldBeRight :: (Show a, Show b, Eq b) => Either a b -> b -> Expectation
shouldBeRight (Right actual) expected = actual `shouldBe` expected
shouldBeRight (Left err) expected =
expectationFailure $
"Expected Right " ++ show expected ++
", but got Left " ++ show err
shouldBeLeft :: (Show a, Show b) => Either a b -> Expectation
shouldBeLeft (Left _) = return ()
shouldBeLeft (Right val) =
expectationFailure $
"Expected Left, but got Right " ++ show val
-- Custom matcher for non-empty lists
shouldBeNonEmpty :: Show a => [a] -> Expectation
shouldBeNonEmpty [] = expectationFailure "Expected non-empty list"
shouldBeNonEmpty _ = return ()
-- Usage
spec :: Spec
spec = describe "validateUser" $ do
it "returns Right for valid user" $ do
validateUser (NewUser "Alice" "alice@example.com")
`shouldBeRight` User { userId = 0, userName = "Alice" }
it "returns Left for invalid email" $ do
shouldBeLeft (validateUser (NewUser "Bob" "not-an-email"))Running Tests with Cabal and Stack
# Stack
stack test
stack test --test-arguments="--match '/UserSpec'" # Filter by spec
# Cabal
cabal test
cabal test --test-options="--match '/UserSpec'"
# Run specific test
stack test --test-arguments="--match '/UserRepository/insert'"Conclusion
HSpec's describe/it structure maps naturally to Haskell's module hierarchy. Use around for database and resource lifecycle, beforeAll for expensive one-time setup, and custom matchers to make failures readable. The auto-discovery with hspec-discover keeps the test entry point minimal as your suite grows.