Hspec: A Testing Framework for Haskell

Contents

Five-step introduction

Step 1: Describe your desired behavior

-- file MathSpec.hs
module MathSpec where

import Test.Hspec
import Math

main :: IO ()
main = hspec $ do
  describe "absolute" $ do
    it "returns the original number when given a positive input" $
      absolute 1 `shouldBe` 1

    it "returns a positive number when given a negative input" $
      absolute (-1) `shouldBe` 1

    it "returns zero when given zero" $
      absolute 0 `shouldBe` 0

Step 2: Write some code

-- file Math.hs
module Math where

absolute :: Int -> Int
absolute = undefined

Step 3: Run and watch it fail

$ runhaskell MathSpec.hs

absolute
  returns the original number when given a positive input FAILED [1]
  returns a positive number when given a negative input FAILED [2]
  returns zero when given zero FAILED [3]

Failures:

  MathSpec.hs:10: 
  1) absolute returns the original number when given a positive input
       uncaught exception: ErrorCall (Prelude.undefined
       CallStack (from HasCallStack):
         error, called at libraries/base/GHC/Err.hs:79:14 in base:GHC.Err
         undefined, called at Math.hs:5:12 in main:Math)

  MathSpec.hs:13: 
  2) absolute returns a positive number when given a negative input
       uncaught exception: ErrorCall (Prelude.undefined
       CallStack (from HasCallStack):
         error, called at libraries/base/GHC/Err.hs:79:14 in base:GHC.Err
         undefined, called at Math.hs:5:12 in main:Math)

  MathSpec.hs:16: 
  3) absolute returns zero when given zero
       uncaught exception: ErrorCall (Prelude.undefined
       CallStack (from HasCallStack):
         error, called at libraries/base/GHC/Err.hs:79:14 in base:GHC.Err
         undefined, called at Math.hs:5:12 in main:Math)

Randomized with seed 921447365

Finished in 0.0005 seconds
3 examples, 3 failures

Step 4: Implement your desired behavior

-- file Math.hs
module Math where

absolute :: Int -> Int
absolute n = if n < 0 then negate n else n

Step 5: Run again and see it pass

$ runhaskell MathSpec.hs

absolute
  returns the original number when given a positive input
  returns a positive number when given a negative input
  returns zero when given zero

Finished in 0.0005 seconds
3 examples, 0 failures