【问题标题】:Run db action in yesod test在 yesod 测试中运行 db 操作
【发布时间】:2017-12-30 05:04:12
【问题描述】:

在我的 yesod 测试中,我希望能够在测试过程中修改数据库中的记录。

这是我想出的代码

        yit "post is created by authorized user" $ do
            request $ do
                addPostParam "ident" "dummy"
                setMethod "POST"
                setUrl ("http://localhost:3000/auth/page/dummy" :: Text)
            update 0 [UserAuthorized =. True]
            postBody PostR (encode $ object [
                "body" .= ("test post" :: Text),
                "title" .= ("test post" :: Text),
                "coverImage" .= ("test post" :: Text),
                "author" .= (0 :: Int)
                ])
            statusIs 200

这会失败并出现错误

• Couldn't match expected type ‘IO a0’
              with actual type ‘ReaderT backend0 m0 ()’
• In the second argument of ‘($)’, namely
    ‘update 0 [UserAuthorized =. True]’

  In a stmt of a 'do' block:
    runIO $ update 0 [UserAuthorized =. True]
  In the expression:
    do { settings <- runIO
                     $ loadYamlSettings
                         ["config/test-settings.yml", "config/settings.yml"] [] useEnv;
         foundation <- runIO $ makeFoundation settings;
         yesodSpec foundation $ do { ydescribe "Auth" $ do { ... } };
         runIO $ update 0 [UserAuthorized =. True];
         .... }

我可以看出这是因为 update 返回 m () 而不是 YesodExample site ()requestpostBodystatusIs 那样。

我怎样才能在这个测试中进行数据库更新?

【问题讨论】:

    标签: haskell testing integration-testing yesod yesod-test


    【解决方案1】:

    您需要使用runDB 函数。即:

    runDB $ update 0  [UserAuthorized =. True]
    

    【讨论】:

    • 这解决了一半,我几乎解决了另一个问题,我将很快发布。
    【解决方案2】:

    这有两个问题,Sibi 指出的第一个问题是我需要runDB,第二个问题是你不能只用整数查找记录。

    为了实现这个功能,我使用了以下代码

    runDB $ do
        (first :: Maybe (Entity User)) <- selectFirst [] []
        case first of
            Nothing -> pure () -- handle the case when the table is empty
            Just (Entity k _) -> update k [UserAuthorized =. True]
    

    此查找是数据库中的记录,然后对其进行更新。修改(first :: Maybe (Entity User)) &lt;- selectFirst [] [],选择要更新的记录。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-18
      • 1970-01-01
      • 1970-01-01
      • 2018-06-28
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多