Created
November 12, 2025 18:42
-
-
Save sellout/96da33483b91a431b9aed2aa8c42417d to your computer and use it in GitHub Desktop.
How to do Rust-like tests in Haskell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| cabal-version: 3.0 | |
| name: rusty-haskell-tests | |
| version: 0.0.1.0 | |
| synopsis: How to do Rust-like tests in Haskell | |
| library | |
| hs-source-dirs: | |
| src | |
| build-depends: | |
| base | |
| exposed-modules: | |
| Simple | |
| test-suite tests | |
| type: exitcode-stdio-1.0 | |
| hs-source-dirs: | |
| src | |
| main-is: Simple.hs | |
| build-depends: | |
| base, | |
| hspec | |
| cpp-options: -DRUSTY_TESTS |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| {-# LANGUAGE CPP #-} | |
| #ifndef RUSTY_TESTS | |
| module Simple where | |
| #endif | |
| import Data.Functor (fmap) | |
| import Data.Int (Int) | |
| import Data.String (String) | |
| import Text.Show (show) | |
| #ifdef RUSTY_TESTS | |
| import Test.Hspec | |
| #endif | |
| simpleMap :: [Int] -> [String] | |
| simpleMap = fmap show | |
| #ifdef RUSTY_TESTS | |
| main :: IO () | |
| main = hspec $ do | |
| describe "simple" $ do | |
| it "does a very simple thing" $ do | |
| simpleMap [1, 2, 3] `shouldBe` ["1", "2", "3"] | |
| it "uh, fails when it should" $ | |
| simpleMap [1, 2, 3] `shouldBe` ["3", "2", "1"] | |
| #endif |
Author
Author
A Cabal feature that would be nice (but maybe violates some fundamental expectations) is if you could specify flags on build-depends, then you wouldn’t need to include the src modules in the test-suite. (NB: This is for the version where you have a separate test driver.)
flag rusty-tests
description: whether to compile the library with its test
code enabled, this is internal and shouldn’t be set externally.
default: False
manual: True
library
hs-source-dirs:
src
build-depends:
base
exposed-modules:
Simple
if flag(rusty-tests)
cpp-options: -DRUSTY_TESTS
test-suite tests
type: exitcode-stdio-1.0
hs-source-dirs:
tests
main-is: test.hs
build-depends:
base,
-- HERE’s THE THING THAT YOU CAN’T CURRENTLY DO
rusty-haskell-tests +rusty-tests,
hspec
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This puts the test driver (
main) directly in the source file.Instead, you could have tests/test.hs or whatever with
mainand then Simple.hs would just define anExpectationterm, and the#ifndefaround the module declaration could be removed.