Search code examples
elixirphoenix-frameworkelixir-mix

Testing controller using fixture with multiple belongs_to relation elixir


I am currently trying to get my tests running smoothly and I am struggeling to get the setup right.

There is: "work_item" that belongs to "user" and to "project"

I can't figure out how to create a fixture that I can use with setup [:work_item] that has the proper relations.

@create_attrs %{
    comment: "some comment",
    date: ~D[2010-04-17],
    duration_in_minutes: 42,
    hourly_rate_in_cents: 42,
    project_id: , #<- THIS ONE
    user_id: #<- &this one}

  def fixture(:work_item) do
      {:ok, work_item} = Tracking.create_work_item(@create_attrs)
    work_item
  end

  def fixture_project(:project) do
    valid_project_attrs = %{name: "Some project"}
    {:ok, project} = Clients.create_project(valid_project_attrs)
    project
  end

# Removed code for readability

defp create_work_item(_) do
    work_item = fixture(:work_item)
    %{work_item: work_item}
  end

  defp create_project(_) do
    project = fixture_project(:project)
    %{project: project}
  end

  defp create_user(_) do
    user = fixture_user(:user)
    %{user: user}
  end

It would be great if someone could elaborate!


Solution

  • What I do is create the related fixtures and then merge the @create_attrs with the attributes for the pointers to the related fixtures

    def fixture(:work_item) do
      project = fixture_project(:project)
      user = fixture_user(:user)
      
      {:ok, work_item} = @create_attrs
      |> Map.merge(%{project_id: project.id, user_id: user.id})
      |> Tracking.create_work_item()
    
      work_item
    end