2016-04-15 24 views
3

我正在構建一個elixir phoenix應用程序,使用自定義數據庫適配器連接到OrientDB。所以我使用--no-ecto選項生成了基本應用程序,因爲我沒有使用Ecto。Elixir/Phoenix:如何在不使用Ecto的情況下對模型進行單元測試?

我正在構建自定義模型和自定義驗證,但當然要做單元測試。

如果我嘗試包括ModelCase在我的單元測試,像這樣:

defmodule App.UserTest do 
    use App.ModelCase 

end 

我得到的錯誤

module App.ModelCase is not loaded and could not be found 

這可能是因爲它是外生的一部分。

如果我不包括它,代碼後來失敗了,告訴我,

undefined function test/2 

我該如何處理呢?

回答

4

簡短回答:代替use App.ModelCase只需使用use ExUnit.Case

長的答案。當創建與外生項目你位於test/support三種不同的測試案例模板:

  • channel_case.ex
  • conn_case.ex
  • model_case。ex

Case templates用於定義可以在每個使用該模板的測試中使用的函數。

例如,model_case定義爲你好:

using do 
    quote do 
    alias App.Repo 

    import Ecto 
    import Ecto.Changeset 
    import Ecto.Query, only: [from: 1, from: 2] 
    import App.ModelCase 
    end 
end 

setup tags do 
    unless tags[:async] do 
    Ecto.Adapters.SQL.restart_test_transaction(App.Repo, []) 
    end 

    :ok 
end 

def errors_on(model, data) do 
    model.__struct__.changeset(model, data).errors 
end 

裏面的一切quote do ... end在你的測試用例的開始注入。如果你不使用Ecto,這根本沒用。第一行別名回購,下一行導入Ecto模塊(您沒有)

設置功能確保測試在事務內部運行,當它們完成時可以回滾,errors_on也是Ecto特定的。這就是爲什麼當您使用--no-ecto運行時,此模塊完全不存在。

所以你有兩個選擇。您可以使用ExUnit.Case這是處理測試的標準方式(您可以通過創建非Phoenix應用程序進行混合檢查),也可以創建自己的App.ModelCase。如果模型測試用例之間有足夠的共享代碼,這可能是一個好主意。

+0

看起來像你在'unless tags [:async]'塊中保存了你的應用程序的名字。可能希望將其更改爲「App.Repo」,以便未來的用戶不會感到困惑。 –

+0

Ups,謝謝指出!改變。 – tkowal

+0

''model_case.ex'似乎已經被'data_case.ex'替代,至少從Elixir 1.5.2開始 –

1

App.ModelCase不會使用--no-ecto選項自動生成。

它本身做use ExUnit.CaseTemplate(See the CaseTemplate docs), 並將import App.ModelCase注入到使用模塊中。它還會導入一些特定於ecto的模塊,但它們對您沒有用處。

在你的情況,你可以定義test/support/model_caseApp.ModelCaseuse ExUnit.CaseTemplate裏面,並定義要定義一個宏using注入用模塊的內容。

只給你的一些東西,你可能想要做的一個想法,這裏有一個例子具體外生版本:

defmodule App.ModelCase do 
    use ExUnit.CaseTemplate 

    using do 
    quote do 
     alias App.Repo 

     import Ecto 
     import Ecto.Changeset 
     import Ecto.Query, only: [from: 1, from: 2] 
     import App.ModelCase 
    end 
    end 

    setup tags do 
    # Setup stuff you want to automatically do before tests 
    end 

    def some_helper_function 
    # helper function stuff goes here 
    # 
    # this function is available in all using modules because of 
    # the `import App.ModelCase` in the using macro. 
    end 
end 

因此,要麼:

  1. 創建文件
  2. 刪除與您的應用無關的內容
  3. 添加自己的內容

或者只是use ExUnit.Case而不是use App.ModelCase。無論哪種方式應該工作。

use ExUnit.Case更簡單。 use App.ModelCase將允許您定義所有使用模塊中可用的幫助程序。

相關問題