Find by id

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

Setup Test

This time in our setup, we are going to return a tuple with the first value being :ok. The other values we provide keys for so we can access in the context argument for our test.

# /test/models/posts/find_by_id_test.exs
defmodule Readdit.Posts.FindByIdTest do
  use ExUnit.Case
  use Readdit.ConnCase

  setup do
    post = %Readdit.Post{title: "Han Shot First"} |> Readdit.Repo.insert!
    
    { :ok, post_id: post.id }
  end

end

Repo.get

We find a record by it’s id using the Repo.get/2 function. The first argument is the Ecto model to retrieve. The second argument is the id.

Notice we when we labeled our test, we added a second argument context. This is passed down from setup. We can then retrieve the id of the inserted record from our setup by accessing the id from our context.

test "find by id", context do
  post = Readdit.Repo.get(Readdit.Post, context[:post_id])

  assert post.title == "Han Shot First"
end

Model |> Repo.get

Isn’t the pipeline operator great? We can use it again to Elixir-ify getting our post record.

Remember the pipeline operator passes the left hand result as the first argument to the right hand function.

test "post |> find by id", context do
  post = Readdit.Post |> Readdit.Repo.get(context[:post_id])

  assert post.title == "Han Shot First"
end

Test Review

Our tests should pass and look like:

# /test/models/posts/find_by_id_test.exs
defmodule Readdit.Posts.FindByIdTest do
  use ExUnit.Case
  use Readdit.ConnCase

  setup do
    post = %Readdit.Post{title: "Han Shot First"} |> Readdit.Repo.insert!
    
    { :ok, post_id: post.id }
  end

  test "find by id", context do
    post = Readdit.Repo.get(Readdit.Post, context[:post_id])

    assert post.title == "Han Shot First"
  end
  
  test "post |> find by id", context do
    post = Readdit.Post |> Readdit.Repo.get(context[:post_id])

    assert post.title == "Han Shot First"
  end

end
Next: Where by field