HSpec中的多个函数之前?

时间:2017-12-16 08:37:53

标签: haskell scotty hspec

我有一个内存存储库,我可以通过调用此函数来创建:

newEmptyRepository :: IO InMemoryGameRepository

其中InMemoryGameRepository的定义如下:

type State = (HashMap GameId Game)
type IORefState = IORef State
newtype InMemoryGameRepository = InMemoryGameRepository IORefState

在为我的Scotty应用程序编写测试时,我已经看到了使用这种方法的示例:

spec =
  before app $ do
    describe "GET /" $ do
      it "responds with 200" $ get "/" `shouldRespondWith` 200
      it "responds with 'hello'" $ get "/" `shouldRespondWith` "hello"
    ...

这一切都很好,但我还需要以某种方式初始化InMemoryGameRepository(通过调用newEmptyRepository)并在我的测试中使用创建的实例。因此,我已将app更改为:

app :: InMemoryGameRepository -> IO Application
app repo = scottyApp $ routes repo

我正在尝试创建一个使用存储库和IO Application的测试,例如像这样(它不起作用):

spec = 
    before (do repo <- newEmptyRepository
               app repo) $ 
      -- API Tests
      describe "GET /api/games" $ 
        it "responds with " $ do
          liftIO $ startGame repo
          get "/api/games" `shouldRespondWith` singleGameResponse

其中startGame的定义如下:

startGame :: InMemoryGameRepository -> IO Game

这里编译器(显然)说repo不在范围内。但是我怎样才能做到这一点?即我想在newEmptyRepository和测试中共享app的单个实例?

Ps:您可以在github上看到完整的应用程序。

1 个答案:

答案 0 :(得分:2)

您应该使用类型为

beforeWith
beforeWith :: (b -> IO a) -> SpecWith a -> SpecWith b

将其用作例如before newEmptyRepository . beforeWith app,其类型为SpecWith Application -> Spec

如果要在测试用例中同时访问InMemoryGameRepositoryApplication,请定义辅助函数

withArg f a = (,) a <$> f a
withArg :: Functor f => (t -> f b) -> t -> f (t, b)

然后使用

before newEmptyRepository . beforeWith (withArg app)
    :: SpecWith (InMemoryGameRepository, Application) -> Spec

最后,你不应该在测试定义中使用liftIO $ startGame repo - 每次构建测试树时都会运行startGame(尽管这可能实际上是你想要的,它似乎并非如此)。相反,如果您使用before系列函数,startGame将在实际运行测试之前运行一次。您甚至可以使用与上述相同的技术访问Game返回的startGame

  before newEmptyRepository 
. beforeWith (withArg startGame) 
. beforeWith (withArg $ app . fst)
:: SpecWith ((InMemoryGameRepository, Game), Application) -> Spec