1

我正在尝试hspec-discover与 custom 一起使用Main。CustomMain是一个创建所有'sbracket使用的文件描述符。Spec

这是我的Spec.hs

{-# OPTIONS_GHC -F -pgmF hspec-discover -optF --module-name=Spec #-}

这是我的Main.hs

module Main (main) where

import Control.Exception
import System.Posix.IO
import System.Posix.Files
import Test.Hspec
import Spec (spec)

main :: IO ()
main = bracket
  (openFd verybigFile ReadWrite (Just 384) defaultFileFlags)
  (\fd -> closeFd fd >> removeLink verybigFile)
  (\fd -> hspec (spec fd))
    where
      verybigFile = "test/verybigFile"

为了让我spec在单个自动发现的模块中接受文件描述符参数,我需要将其声明为

spec :: Fd -> Spec

hspec-discover要求将规范声明为

spec :: Spec

否则自动生成的模块无法编译:

test/Spec.hs:8:68:
    Couldn't match type `System.Posix.Types.Fd -> Spec'
                  with `hspec-core-2.1.7:Test.Hspec.Core.Spec.Monad.SpecM () ()'
    Expected type: hspec-core-2.1.7:Test.Hspec.Core.Spec.Monad.SpecWith
                     ()
      Actual type: System.Posix.Types.Fd -> Spec
    In the second argument of `describe', namely `SendfileSpec.spec'
    In the second argument of `postProcessSpec', namely
      `(describe "Sendfile" SendfileSpec.spec)'
    In the expression:
      postProcessSpec
        "test/SendfileSpec.hs" (describe "Sendfile" SendfileSpec.spec)

那么,如何在不干扰自动发现的情况下将参数传递给规范?我的想像飘向IORef',但这个想法让我不寒而栗。什么是正确的方法?

4

1 回答 1

3

当前不支持跨规范文件共享值hspec-discover。但是您仍然可以在同一个规范文件中共享值。以下作品:

FooSpec.hs

module FooSpec (spec) where

import           Test.Hspec
import           System.IO

spec :: Spec
spec = beforeAll (openFile "foo.txt" ReadMode) $ afterAll hClose $ do
  describe "hGetLine" $ do
    it "reads a line" $ \h -> do
      hGetLine h `shouldReturn` "foo"

    it "reads an other line" $ \h -> do
      hGetLine h `shouldReturn` "bar"

Spec.hs

{-# OPTIONS_GHC -F -pgmF hspec-discover #-}

但请注意,这beforeAll通常被认为是代码异味。before如果可能,最好使用它。

于 2015-06-03T23:58:05.493 回答