assert the size of the list in elixir

36,224

Kernel.length/1 will return the size of a list:

length([1,2,3]) #3

You can do this from an Ecto query using:

query = from d in Device, where: d.uuid == ^uuid, select: fragment("count(?)", d.id)
assert  Repo.all(query)== 3

In Ecto 2 you can use Repo.aggregate/4

query = from d in Device, where: d.uuid == ^uuid)
assert Repo.aggregate(query, :count, :id) == 3
Share:
36,224
almeynman
Author by

almeynman

Updated on May 25, 2020

Comments

  • almeynman
    almeynman almost 4 years

    I would like to assert list's size. Currently I do it as follows:

    assert devices = Repo.all from d in device, where d.uuid == ^attrs.uuid
    assert devices.first == devices.last
    

    Is there a better way to do that?

  • Sasha Fonseca
    Sasha Fonseca almost 8 years
    is there any difference/benefit from using Enum,count or Kernel.length?
  • Gazler
    Gazler almost 8 years
    They use the exact same function github.com/elixir-lang/elixir/blob/v1.2.5/lib/elixir/lib/… github.com/elixir-lang/elixir/blob/v1.2.5/lib/elixir/lib/… - you skip a pattern match when using length. I will update the answer to use length instead.
  • michalmuskala
    michalmuskala almost 8 years
    I would also suggest doing assert [devide] = Repo.all(...) if you need the record and want to make sure there's just one.
  • almeynman
    almeynman almost 8 years
    @michalmuskala Thanks I forgot about that
  • Ville
    Ville over 6 years
    count vs. length is discussed in this blog post. The blog author's point in TL;DR is: »length is more preferred way to get length of the list, but it is better to use count for enumerations: streams, ranges, custom iterators» (see the post for his reasoning on why).