Access a value set up by `beforeAll` during tests
Asked Answered
U

1

8

Here's what I've got:

spec :: Spec
spec = do
  manager <- runIO newManager

  it "foo" $ do
    -- code that uses manager

  it "bar" $ do
    -- code that usees manager

The docs for runIO suggest that I should probably be using beforeAll instead, since I do not need manager to construct the spec tree, I just need it to run each test, and in my use case it's better for them to all share the same manager rather than creating a new one for each test.

If you do not need the result of the IO action to construct the spec tree, beforeAll may be more suitable for your use case.

beforeAll :: IO a -> SpecWith a -> Spec

But I can't figure out how to access the manager from the tests.

spec :: Spec
spec = beforeAll newManager go

go :: SpecWith Manager
go = do
  it "foo" $ do
    -- needs "manager" in scope
  it "bar" $ do
    -- needs "manager" in scope
Unideaed answered 29/5, 2015 at 18:8 Comment(0)
S
11

Spec arguments are passed to your it blocks as regular function arguments (look at the associated type of the Example type class, if you want to understand what's going on). A fully self-contained example would be:

import           Test.Hspec

main :: IO ()
main = hspec spec

spec :: Spec
spec = beforeAll (return "foo") $ do
  describe "something" $ do
    it "some behavior" $ \xs -> do
      xs `shouldBe` "foo"

    it "some other behavior" $ \xs -> do
      xs `shouldBe` "foo"
Stiffler answered 31/5, 2015 at 6:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.