Hi everyone,
I had the following idea regarding testing, after I read more on EX Unit docs and also work with it a bit.
Would it be possible to use decorators to create the tests inside the actual file like this?
Here is a schema:
defmodule Phx.Accounts.User do
use Ecto.Schema
import Ecto.Changeset
schema "users" do
field :name
field :email
field :age, :integer
end
def changeset(user, params \\ %{}) do
user
|> cast(params, [:name, :email, :age])
|> validate_required([:name, :email])
|> validate_format(:email, ~r/@/)
|> validate_inclusion(:age, 18..100)
|> unique_constraint(:email)
end
end
And here we have a context for User
defmodule Phx.Accounts do
import Ecto.Query, warn: false
alias Phx.Repo
alias Phxl.Accounts.User
@doc
"""
Below is my proposition of testing in the same file
@list_users = multiple_users with this code we tell phoenix that we want a list of multiple_users if false
complain and fail test
"""
@list_users = multiple_users
def list_users do
Repo.all(User)
end
@doc
"""
Below is my proposition of testing in the same file
@user = insert_user_one_valid with this code we tell phoenix that we want a single user inserted if the
changeset is true if false complain and fail test
"""
@user = insert_user_one_valid
def insert_user(attrs, %{}) do
%User{}
|> User.changeset(attrs)
|> repo.insert()
end
end
UPDATE thanks to @yourpalal for clarification reasons
Instead of this
describe "User.registration_changeset/2" do
@invalid_attrs %{}
test "changeset with invalid attributes" do
changeset = User.registration_changeset(%User{}, @invalid_attrs)
refute changeset.valid?
end
USE THIS
@doc
"""
Below is my proposition of testing in the same file
@user = insert_user_one_valid with this code we tell phoenix that we want a single user inserted if the
changeset is true if false complain and fail test
"""
@user = insert_user_one_valid
def insert_user(attrs, %{}) do
%User{}
|> User.changeset(attrs)
|> repo.insert()
end
end
Before i end this proposition, I want to say that if this kind of testing will be created and adopted. Every user will create tests because it will actually be fun and easy.
What do you think about this idea?
Thanks in advanced for any opinions suggestions and criticism