I’m pleased to announce the initial release of AssertIdentity. It’s a small helper library for ExUnit that provides assertions useful for comparing data structures by identity.
AssertIdentity really shines in applications that leverage Ecto. Consider the following:
def MyApp.PostTest do
use MyApp.DataCase
test "list_posts/0 returns all posts" do
post = insert(:post)
assert Posts.list_posts() == [post]
assert_ids_match(Posts.list_posts(), [post])
end
end
The first assertion fails when using factories that, for example, insert associations. (That’s because on the left-hand side you’ll have Ecto.Association.NotLoaded
for the association values but on the right-hand side you’ll have a real association struct.)
The assert_ids_match/2
assertion passes because it instead plucks the :id
key from each struct and compares those values (instead of an identity comparison on the whole struct).
This started as a single helper in one application but we kept pulling it into every Elixir app we’ve worked on so we decided to release it. Perhaps you’ll find it useful too!
Check out the docs for more examples and options on how to customize the identity assertion to your needs! And, of course, feel free to open bug reports or enhancement PRs on GitHub.
Links: