0

Following up on Making a field unique in ecto and Testing Validations in Elixir and Ecto, I am failing to setup a controller test for unique constraints:

test "POST /imports will not store duplicate address" do
  # Create the existing (conflicting) record:
  location = "melee island"
  MyApp.Repo.insert! %MyApp.Location{address: location}

  post("/imports", %{"location" => location})

  # Other assertions omitted

  # Check if the location was indeed NOT inserted
  query = from l in MyApp.Location,
    where: [address: ^location],
    select: l.address

  assert MyApp.Repo.all(query) == [location]
end

The last assertion fails with the following error:

(Postgrex.Error) ERROR (in_failed_sql_transaction): current transaction is aborted, commands ignored until end of transaction block

I understand why – everything is wrapped into a test transaction – but I cannot rollback without losing the initially inserted record. Is there a way to get this behaviour tested?

Community
  • 1
  • 1
Carsten
  • 531
  • 4
  • 15
  • Can you also post your controller code? The correct way to use `unique_constraint` is to match on value returned by `Repo.insert` in your controller. This shouldn't throw errors at all. – tkowal Jun 22 '16 at 17:45
  • The `unique_constraint` works alright and the corresponding unit test works nicely. It's just that I cannot do anything with `Repo` after the DB transaction failed at the attempt to insert a duplicate key. – Carsten Jun 22 '16 at 19:39

0 Answers0