【问题标题】:"Cannot begin test transaction because we are already inside one"“无法开始测试交易,因为我们已经在其中”
【发布时间】:2015-06-03 17:15:00
【问题描述】:

我关注了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。但找不到任何修复方法。

附言。我正在使用 Postgresql

【问题讨论】:

  • 您对此问题的解决方法是什么?我刚刚从 Phoenix_Ecto 0.3 更新到 0.4,现在我在每次测试中都遇到了这个问题 :( - 即使在我不使用控制器的模型测试中
  • 就像@JoseValim 说的。删除带有测试事务的整个部分。 ExUnit 会在一些更新后自动完成

标签: elixir phoenix-framework ecto


【解决方案1】:

您使用的是最新的 Phoenix 吗?如果是这样,它应该已经生成了test/support/conn_case.ex,它已经包含了运行控制器测试所需的所有步骤。你只需要在你的测试中做use YourApp.ConnCase。这篇博文是在测试基础设施到位之前编写的。 :)

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

【讨论】:

  • 是的。一如既往,你是第一个何塞。非常感谢:D
猜你喜欢
  • 1970-01-01
  • 2020-12-27
  • 1970-01-01
  • 2021-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-16
相关资源
最近更新 更多