Reading Many to Many

Ecto for Beginners : part 18 of 22 published on Sep 07, 2015
defmodule Readdit.Tags.InsertTest do
  use ExUnit.Case
  use Readdit.ConnCase

  setup do
    post = %Readdit.Post{title: "Han Shot First"} |> Readdit.Repo.insert!
    tag = %Readdit.Tag{title: "scifi"} |> Readdit.Repo.insert!

    %Readdit.Tagging{
      post_id: post.id, 
      tag_id: tag.id
    } |> Readdit.Repo.insert!

    { :ok, post_id: post.id, tag_id: tag.id }
  end
  
  test "tag added to post", context do
    post = Readdit.Post 
      |> Readdit.Repo.get(context[:post_id])
      |> Readdit.Repo.preload(:tags)

    assert post.title == "Han Shot First"
    assert Enum.count(post.tags) == 1
  end

  test "post added to tag", context do
    tag = Readdit.Tag 
      |> Readdit.Repo.get(context[:tag_id])
      |> Readdit.Repo.preload(:posts)

    assert tag.title == "scifi"
    assert Enum.count(tag.posts) == 1
  end
  
end
Next: Count