Exunit test assertion failure error

Hello everyone, I am new to Elixir and I am trying to build a Blog application for which I am writing some tests.

The schema is like this:

  • Post Schema:
    field :post_title, :string
    has_many :comments, MyApp.Blogs.Comment

  • Comment Schema:
    field :comment_body, :string
    belongs_to :post, MyApp.Blogs.Post

The list function for the post in blog.ex file is defined as follows:

def list_posts do
    Repo.all(from p in Post, join: c in assoc(p, :comments), preload: [comments: c])

The blogs.exs file is as follows

test "list_posts/0 returns all posts" do
      post = post_fixture()
      assert Blogs.list_posts() == [post]

I get assertion failed error “Assertion with == failed”. The LHS is empty whereas the RHS has a single element. I am unable to figure out how to resolve this, and also I would like to test by expanding the post list on RHS to see if it returns multiple posts.

Hello and welcome,

You should check what post_fixture() returns… and maybe show this function…

…and also Blogs.list_questions().

Thank you, this is what the post_fixture() returns

def post_fixture(attrs \\ %{}) do
      {:ok, post} =
        |> Enum.into(@valid_attrs)
        |> Blogs.create_post()


and Blogs.list_questions()

BTW Why isn’t it Blogs.list_posts?

I was asserting with another schema in the application which I then modified to Blogs.list_posts() so the list_post() test asserts only Blogs.list_posts().

This produces an inner join, so only posts with comments will be retrieved. post_fixture does not have a comment, so list_posts returns [].


I am not sure what exactly is the syntax to include has_many and belongs_to associations to valid attributes

Posts should be fine to test once you fix the issue brought up by @al2o3cr (replace join with full_join in your query). To test comments, you will have to use something like

post = post_fixture()
comment = comment_fixture(%{post_id: post.id})

to ensure that the comment can reference a valid post.