为什么在setup_all块中的数据库中插入的对象不会出现在测试块中?

时间:2016-12-23 23:01:31

标签: elixir ecto ex-unit

我在控制器中有类似的测试,测试块中有setup_all个插件。在这里,我试图在我的模型中允许相同的东西,但我似乎无法使其发挥作用。

我的测试如下:

defmodule Faq.QuestionTest do
  use Faq.ModelCase

  alias Faq.Question

  setup_all do
    :ok = Ecto.Adapters.SQL.Sandbox.checkout(Repo)

    Question.changeset(%Question{}, %{question: "Unanswered", answer: nil})                                                           |> Repo.insert!
    Question.changeset(%Question{}, %{question: "Answered",   answer: "My published answer", published_at: Ecto.DateTime.utc(:usec)}) |> Repo.insert!

    published_count = Question |> Question.published |> Repo.all |> Enum.count
    assert 1 == published_count

    IO.puts "SETUP_ALL"

    :ok
  end

  describe "scopes" do
    test "answered", meta do
      published_count = Question |> Question.published |> Repo.all |> Enum.count
      assert 1 == published_count
    end
  end
end

当我运行它时,我有以下错误:

$ mix test test/models/question_test.exs
warning: variable meta is unused
  test/models/question_test.exs:21

SETUP_ALL


  1) test scopes answered (Faq.QuestionTest)
    test/models/question_test.exs:21
    Assertion with == failed
    code: 1 == published_count
    lhs:  1
    rhs:  0
    stacktrace:
      test/models/question_test.exs:23: (test)



Finished in 0.09 seconds
1 test, 1 failure

现在在setup_all块中,我进行了与test块中相同的验证。为什么它会在测试中失败但是传入setup_all

1 个答案:

答案 0 :(得分:0)

事实证明,ModelCase在每次运行时再次运行setup_all的第一行,从而使我的连接无效。这一行就在这里::ok = Ecto.Adapters.SQL.Sandbox.checkout(Repo)