Hspec: A Testing Framework for Haskell

Getting started

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:

  _includes/introduction/MathSpec.hs:10: 
  1) absolute returns the original number when given a positive input
       uncaught exception: ErrorCall (Prelude.undefined)

  _includes/introduction/MathSpec.hs:13: 
  2) absolute returns a positive number when given a negative input
       uncaught exception: ErrorCall (Prelude.undefined)

  _includes/introduction/MathSpec.hs:16: 
  3) absolute returns zero when given zero
       uncaught exception: ErrorCall (Prelude.undefined)

Randomized with seed 1056294642

Finished in 0.0053 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.0033 seconds
3 examples, 0 failures