Ecto assert_raise test I don't understand why it fails

Hi,

I’m trying to test some code that should fail if the underlying Ecto query raises because no records were found.

The test is the following:

test "fails if given node does not exist" do
    assert_raise(Ecto.NoResultsError, Registration.get_registry!("invalid node"))
end

And the subject:

  def get_registry!(node) do
    PushRegistry |> Repo.get_by!(node: node)
  end

Running the test leads to:

  1) test get_registry!/1 fails if given node does not exist (PushRegistryTest)
     apps/push_registry/test/push_registry_test.exs:44
     ** (Ecto.NoResultsError) expected at least one result but got none in query:
     
     from p0 in PushRegistry.Registration.PushRegistry,
       where: p0.node == ^"invalid node"
     
     code: assert_raise(Error, Registration.get_registry!("invalid node"))
     stacktrace:
       (ecto 3.4.2) lib/ecto/repo/queryable.ex:122: Ecto.Repo.Queryable.one!/3
       test/push_registry_test.exs:45: (test)

It’s my very first Ecto app and I cannot see what I’m doing wrong. I’ll really appreciate any hint here.

Thanks!

assert_raise expects a function. Try:

test "fails if given node does not exist" do
  assert_raise Ecto.NoResultsError, fn ->
    Registration.get_registry!("invalid node")
  end
end
5 Likes

That was it, thank you!