Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Cannot begin test transaction because we are already inside one"

I followed this tutorial and my simple test always fail with this error

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    

The code is quite simple

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

I googled all over the error cannot begin test transaction because we are already inside one. But couldn't find any fix.

PS. Im using Postgresql

like image 407
Krzysztof Wende Avatar asked Jun 03 '15 17:06

Krzysztof Wende


1 Answers

Are you using latest Phoenix? If so, it is supposed to have generated test/support/conn_case.ex which already has all the steps required to run your controller tests. You just need to do use YourApp.ConnCase in your tests. The blog post was written before the testing infrastructure was in place. :)

That said, the reason is likely because test/test_helper.exs already has a call to begin_test_transaction.

like image 182
José Valim Avatar answered Oct 13 '22 01:10

José Valim