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

aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
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
Phillipp
Hey, I have a NanoPi-M3 and try to install Elixir on their Ubuntu image. I followed the Raspberry Pi installation instructions from the ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
idi527
I’ve been re-reading swift book again and noticed that multiline strings there don’t have a trailing line break, unlike in elixir iex(2)...
New

Other popular topics Top

dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement