“无法开始测试交易,因为我们已经在一个内部”

时间:2015-06-03 17:15:00

标签: elixir phoenix-framework ecto

我跟着this tutorial,我的简单测试总是因此错误而失败

1) test /index returns a list of contacts (WorldNote.ChatsControllerTest)                                             
     test/controllers/chats_controller_test.exs:16                                                                      
     ** (RuntimeError) cannot begin test transaction because we are already inside one                                  
     stacktrace:                                                                                                        
       (ecto) lib/ecto/adapters/sql.ex:321: anonymous fn/6 in Ecto.Adapters.SQL.start_test_transaction/3                
       (ecto) lib/ecto/adapters/sql.ex:615: Ecto.Adapters.SQL.pool_transaction/4                                        
       (ecto) lib/ecto/adapters/sql.ex:314: Ecto.Adapters.SQL.start_test_transaction/3                                  
       test/controllers/chats_controller_test.exs:9: WorldNote.ChatsControllerTest.__ex_unit_setup_0/1                  
       test/controllers/chats_controller_test.exs:1: WorldNote.ChatsControllerTest.__ex_unit__/2    

代码非常简单

defmodule WorldNote.ChatsControllerTest do
  use ExUnit.Case, async: false
  use Plug.Test
  alias WorldNote.Chats
  alias WorldNote.Repo
  alias Ecto.Adapters.SQL

  setup do
    SQL.begin_test_transaction(Repo)

    on_exit fn ->
      SQL.rollback_test_transaction(Repo)
    end
  end

  test "/index returns a list of contacts" do
    contacts_as_json =
      %Chats{fbid: 1234567890, latitude: 0.0, longitude: 0.0, content: "yo"}
      |> Repo.insert
      |> List.wrap
      |> Poison.encode!

    response = conn(:get, "/api/contacts") |> send_request

    assert response.status == 200
    assert response.resp_body == contacts_as_json
  end

  defp send_request(conn) do
    conn
    |> put_private(:plug_skip_csrf_protection, true)
    |> WorldNote.Endpoint.call([])
  end
end

我搜索了错误cannot begin test transaction because we are already inside one。但找不到任何解决办法。

PS。我正在使用Postgresql

1 个答案:

答案 0 :(得分:19)

您使用的是最新凤凰吗?如果是这样,它应该生成test/support/conn_case.ex,它已经具有运行控制器测试所需的所有步骤。您只需要在测试中执行use YourApp.ConnCase。博客文章是在测试基础架构到位之前编写的。 :)

也就是说,原因可能是因为test/test_helper.exs已经调用了begin_test_transaction