haskellcabalhaskell-stackhspec

Using HSpec with Stack


I have the following architecture :

  backend
  ├── Chat.hs
  ├── Main.hs
  └── Message.hs
  test
  ├── backendSpec
  │   └── MessageSpec.hs
  └── Spec.hs

My .cabal file contains the following

test-suite spec
  build-depends:  base, hspec == 2.*,
                  snap >= 0.14.0.6,
                  containers,
                  aeson,
                  text,
                  transformers,
                  stm,
                  snap-core,
                  snap-server,
                  socket-io,
                  engine-io-snap,
                  snap-cors,
                  bytestring
  hs-source-dirs: test
  main-is: Spec.hs
  Type: exitcode-stdio-1.0

but when I do

stack test

HSpec cannot find my test int MessageSpec.hs.

Finished in 0.0002 seconds 0 examples, 0 failures

Spec.hs is the correct input : {-# OPTIONS_GHC -F -pgmF hspec-discover #-}

and my MessageSpec module is exposing : module MessageSpec (main, spec).

Could you help me find a way to make my stack project doing all my tests.

Thank you,


Solution

  • Your path to your spec must follow the module name convention. backendSpec.MessageSpec is not a valid module name, since it starts with a lowercase letter.

    Furthermore, the module name of your spec should only differ by the additional suffix Spec from your original module. Your modules in backendSpec wouldn't follow this:

    module Message where ...
    -- vs
    module BackendSpec.MessageSpec where ...
    

    So to fix this, make sure that all directories in your test directory start with an uppercase letter. But even better, make sure that the test directory has the same structure as your src directory, as this will result in better module names during your tests:

    -- If file is test/BackendSpec/MessageSpec.hs
    BackendSpec.Message:
       <someDescription>
          <some assertion>
          <some assertion>
          <some assertion>
    

    vs

    -- If file is test/MessageSpec.hs
    Message:
       <someDescription>
          <some assertion>
          <some assertion>
          <some assertion>
    

    (The relevant code for this behaviour can be found in hspec/Run.hs of hspec-discover)