Releasing Assert Identity

May 06, 2020

Tags: Elixir, Open Source, Programming

I’m pleased to announce a new Elixir library called 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. Let’s take a look.

First, add the package to your mix.exs file:

def deps do
  [
    {:assert_identity, "~> 0.1.0", only: :test}
  ]
end

Then, in a test file:

def MyApp.PostTest do
  use MyApp.DataCase

  test "list_posts/0 returns all posts" do
    post = insert(:post)
    assert_ids_match(Posts.list_posts(), [post])
  end
end

The test provided by the standard Phoenix generators would be assert Posts.list_posts() == [post], however that test 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. Because the values are different, the assertion fails.

The assert_ids_match/2 assertion will instead pluck the :id key from each struct and compare those only. From a data-correctness perspective, we just care that the primary keys match, so this assertion is sufficient.

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 the docs for even more examples and, of course, feel free to open bug reports or enhancement PRs on GitHub.

Links

Logan Leger

Founder & CEO

Founder. Engineer and entrepreneur. Husband and father. Writes in Ruby, Elixir, JavaScript, and Swift.

let's talk.

Together we can make something great.

contact us about new work

Contact

225-407-4520

hello@newaperio.com

Visiting Address

640 Main Street, Suite B

Baton Rouge, Louisiana 70801

Social Media