Simplify tests where Either or Maybe types are returned from monadic code

LTS Haskell 22.28:
Stackage Nightly 2024-07-13:
Latest on Hackage:

See all snapshots benri-hspec appears in

BSD-3-Clause licensed by Tim Emiola
Maintained by [email protected]
This version can be pinned in stack with:benri-hspec-,2275

Module documentation for

Depends on 2 packages(full list with versions):
Used by 1 package in nightly-2024-07-13(full list with versions):
# benri-hspec

[![GitHub CI](](
[![Stackage Nightly](](
[![Hackage Dependencies][hackage-deps-badge]][hackage-deps]

`benri-hspec` is a small library of __convenient__ functions for writing hspec tests.

It's simplifies test code that returns `Either` or `Maybe` types from monadic code.

## Example

{-# LANGUAGE OverloadedStrings #-}

import System.Environment
( lookupEnv,
import Text.Read (readEither)
import Test.Hspec
import Test.Hspec.Benri

spec :: Spec
spec = describe "Checking the functions in Test.Hspec.Benri" $ before_ clearIt $ do
context "endsJust_" $ do
it "should succeed if a Just is returned" $ do
endsJust_ getIt

context "endsJust" $ do
it "should match the Just value" $ do
getIt `endsJust` "1"

context "endsNothing" $ do
it "should succeed when the action returns Nothing" $ do
getIt `endsJust` "1"
endsNothing getIt

context "endsLeft_" $ do
it "should succeed if a Left is returned" $ do
endsLeft_ getAsInt

context "endsLeft" $ do
it "should match the Left value" $ getAsInt `endsLeft` "not set!"

context "endsRight_" $ do
it "should succeed if a Right is returned" $ do
endsRight_ getAsInt

context "endsRight" $ do
it "should match the Right value" $ do
getAsInt `endsRight` 1

context "endsThen" $ do
it "should implement the behaviour of the other functions easily" $ do
getIt `endsThen` (== (Just "1"))
getIt `endsThen` (== Nothing)
getAsInt `endsThen` (== (Left "not set!"))
getAsInt `endsThen` (== (Right 1))

getIt :: IO (Maybe String)
getIt = lookupEnv envName

getAsInt :: IO (Either String Int)
getAsInt = maybe (Left "not set!") readEither <$> getIt

setIt :: IO ()
setIt = setEnv envName "1"

setNotInt :: IO ()
setNotInt = setEnv envName "foo"

clearIt :: IO ()
clearIt = unsetEnv envName

envName :: String
envName = "AN_ENV_VAR"

main :: IO ()
main = hspec spec


[hackage-deps-badge]: <>
[hackage-deps]: <>
[hackage-badge]: <>
[hackage]: <>


Revision history for benri-hspec

benri-hspec uses PVP Versioning. – 2024-07-10

  • Add a tested-with field with the CI-test ghc versions – 2024-02-28

  • Reformated, enabled doctests by default – 2022-12-23

  • Added doctests along with other documentation fixes – 2022-11-10

  • Initial version.