Count

Ecto for Beginners : part 19 of 22 published on Sep 07, 2015
# /test/models/posts/count_test.exs
defmodule Readdit.Posts.CountTest do
  use ExUnit.Case
  use Readdit.ConnCase
  import Ecto.Query

  setup do
    %Readdit.Post{title: "Han Shot First"} |> Readdit.Repo.insert!
    %Readdit.Post{title: "Han Shot First"} |> Readdit.Repo.insert!
    %Readdit.Post{title: "R2D2 is the best!"} |> Readdit.Repo.insert!
    %Readdit.Post{title: "Rosetta Stone for Wookies"} |> Readdit.Repo.insert!

    :ok
  end

  test "count" do
    count = Readdit.Post
    |> select([p], count(p.id))
    |> Readdit.Repo.one

    assert count == 4
  end

  test "where title |> count" do
    count = Readdit.Post
    |> where([p], p.title == "Han Shot First")
    |> select([p], count(p.id))
    |> Readdit.Repo.one

    assert count == 2
  end

end
Next: Update all