Midje provided not stubbing function in Compojure / Ring handler

自作多情 提交于 2019-12-11 11:04:09

问题


I'm attempting to use Midje to stub the view in a handler unit test, but my use of Midje's (provided) obviously isn't correct.

I've simplified and inlined the view to a (content) function in the handler:

(ns whattodo.handler
  (:use compojure.core)
  (:require [whattodo.views :as views]))

(defn content [] (views/index))

(defn index [] (content))

(defroutes app
  (GET "/" [] (index)))

and am trying to test it using

(ns whattodo.t-handler
  (:use midje.sweet)
  (:use ring.mock.request)
  (:use whattodo.handler))

(facts "It returns response"
       (let [response (app (request :get "/"))]
         (fact "renders index view" (:body response) => "fake-html"
               (provided (#'whattodo.handler/content) => (fn [] "fake-html")))))

I was expecting the stubbed function to be called returning 'fake-html' and thus the unit test passing, but instead, the test fails as the real implementation is called - invoking the real view.


回答1:


You don't need the function shortcut, just use (content) => .... As you have it right now, midje expects that your code calls literally (#content), but your index function calls (content) instead. Your confusion about midje's syntax might be that you expect that you assign to the function name the expected result, but that is not the case. You have to replace the exact call. I.e., if your index function would call content with some argument, you would have to account for this as well, e.g. by (provided (content "my content") => ...)




回答2:


I discovered today that I had my scopes confused - the let block introducing response was outside of the fact call that included the provided. Thus the response was created before the provided was invoked.

Working code which passed this early test instead used the against-background call

(facts "It returns response"                                                                                                                          
   (against-background (whattodo.handler/content) => "fake-html")                                                                                 
   (let [response (app (request :get "/"))]                                                                                                       
     (fact "renders index view"                                                                                                                   
           (:body response) => "fake-html")))


来源:https://stackoverflow.com/questions/28528474/midje-provided-not-stubbing-function-in-compojure-ring-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!