Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a value set up by `beforeAll` during tests

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
like image 415
Dan Burton Avatar asked May 29 '15 18:05

Dan Burton


1 Answers

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"
like image 68
Simon Hengel Avatar answered Oct 18 '22 02:10

Simon Hengel