Get all records

Ecto for Beginners : part 8 of 22 published on Sep 06, 2015

Setup Test

With ExUnit, we can do an initial setup for all our tests inside a setup. For this test we are going to insert 3 records into the database before each test.

Be sure to return :ok with your setup code.

# /test/models/posts/all_test.exs
defmodule Readdit.Posts.AllTest do
  use ExUnit.Case
  use Readdit.ConnCase

  setup do
    %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
end

Repo.all

To return all the records for a model, we use the Repo.all/1 function. The first parameter to return all the results is our model in this case Post.

test "all" do
  posts = Readdit.Repo.all(Readdit.Post)

  assert Enum.count(posts) == 3
end

Model |> Repo.all

We can again leverage the |> operator again to simplify our code.

test "post |> all" do
  posts = Readdit.Post |> Readdit.Repo.all

  assert Enum.count(posts) == 3
end

Test Review

In the end, our tests all pass and the file looks like:

# /test/models/posts/all_test.exs
defmodule Readdit.Posts.AllTest do
  use ExUnit.Case
  use Readdit.ConnCase

  setup do
    %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 "all" do
    posts = Readdit.Repo.all(Readdit.Post)

    assert Enum.count(posts) == 3
  end
  
  test "post |> all" do
    posts = Readdit.Post |> Readdit.Repo.all

    assert Enum.count(posts) == 3
  end

end
Next: Find by id