mathew4509

mathew4509

Elixir test case to check if field is empty or invalid

Hi Elixir community, I am a newbie at Elixir and learning to write some effective tests for my blog application. My blog application has the following association:

Post → has_many comments
User → has_many comments
Comment → belongs to post and user
I would like to test

  1. if the post_id in my comment is available/empty and raise appropriate error
  2. if it(post_id) has invalid attribute and if yes, raise appropriate error

CODE:

lib>myapp>blog>comments>comment.ex

@required_field [
:comment_text, :string,
:post_id
]

schema

field :comment_text, :string,
belongs_to :post, Post
belongs_to :user, User

changeset

def changeset(comment, attrs) do
    comment
    |> foreign_key_constraint(:post_id)
    |> foreign_key_constraint(:user_id)
    |> cast(attrs, @required_field ++ @optional_field)
    |> validate_required(@required_field)
  end

I am using factories so no fixtures.

test>support>factory.ex

def comment_factory do
    %Comment{
      comment_text: "some comment_text",
      post: build(:post),
      user: build(:user)
    }
  end

test>myapp>blog>comments_test.exs

    @valid_attrs %{
      comment_text: "some comment text"
    }

Thanks in advance :smiley:

Most Liked

amnu3387

amnu3387

If I’m not mistaken, when you account for a foreign constraint on the changeset, |> foreign_key_constraint(:post_id) like you did the insertion if invalid will fail and the changeset will be marked as errored, so something like

assert {:error, Ecto.Changeset{}} = insert(:comment, @invalid_attrs)

should be what you’re looking for. If you want it to raise then you shouldn’t set the foreign constraint check, and leave it to the database to error, which will make ecto throw and exception.

But I think usually it’s preferable to have no exception and deal with {:ok, _}/{:error, _}.
If then wanted the caller can raise a specific one.

You can also check that the error is in the field you expect along with its message.
You would probably have some helper in your codebase for transforming errored changesets into a map of field => errors.

Ecto.Changeset.traverse_errors/2
With this you can build a simple helper:

def as_error_map(Ecto.Changeset{valid?: false} = changeset) do
  Ecto.Changeset.traverse_errors(changeset, fn {msg, opts} ->
    Enum.reduce(opts, msg, fn {key, value}, acc ->
      String.replace(acc, "%{#{key}}", to_string(value))
    end)
  end)
end

And now you can use assert %{post_id: ["post doesn't exist"]} = as_error_map(changeset)

Where Next?

Popular in Questions Top

WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
yawaramin
In the Dialyzer docs ( dialyzer — OTP 29.0.2 (dialyzer 6.0.1) ), there is a way to turn off a specific warning for a function: -dialyzer...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New

Other popular topics Top

New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement