Writing Yesod test case for handler with an id parameter, where id is a key to an Entity

StackOverflow https://stackoverflow.com/questions/22172573

  •  03-06-2023
  •  | 
  •  

Question

I have been following the yesod tutorial and I am stuck on how to build a unit test involving parameters in a view that also hit a database. Backtracking a little, I followed the Echo.hs example:

    getEchoR :: Text -> Handler Html
    getEchoR theText = do
        defaultLayout $ do
            $(widgetFile "echo")

The corresponding test, note I have to cast the parameter into Text using Data.Text.pack

    yit "Echo some text" $ do
        get $ EchoR $ pack "Hello"
        statusIs 200

Now I have the model defined like so:

Tag
    name Text
    type Text

With a handler that can render that that obviously take a TagId as the parameter

    getTagR :: TagId -> Handler Html
    getTagR tagId = do
        tag <- runDB $ get404 tagId
        defaultLayout $ do
            setTitle $ toHtml $ tagName tag
            $(widgetFile "tag")

This is where the test fails.

    yit "Get a tag" $ do
        -- tagId is undefined
        get $ TagR tagId
        statusIs 200

I am not sure how to define the tagId. It wouldn't work with a String or Text or Num, and I can't seem to figure out how to generate one as I can't find any example code in various Data.Persist tutorials. Or better yet, some other way to call the get method.

Was it helpful?

Solution

You want to use the Key data constructor to construct an ID value, which takes a PersistValue as a parameter. A simple example of creating one is:

Key $ PersistInt64 5

Another option is to call get with a textual URL, e.g. get ("/tag/5" :: Text).

OTHER TIPS

Since times have changed, I'll leave this note here to say that these days one would use something like:

fromBackendKey 5

See the docs for fromBackendKey.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top