Last active
February 11, 2020 22:02
-
-
Save TylerPachal/add1072fc2a7ed70c0c8552461f8f5c6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Demo do | |
use ExUnit.Case | |
# The macro comes from here | |
import TestHelper | |
# An example Ecto Schema for us to play around with | |
defmodule Person do | |
use Ecto.Schema | |
alias Ecto.Changeset | |
@primary_key false | |
embedded_schema do | |
field :name, :string | |
field :age, :integer | |
end | |
def changeset(struct, params) do | |
struct | |
|> Changeset.cast(params, [:name, :age]) | |
|> Changeset.validate_required([:name, :age]) | |
|> Changeset.validate_number(:age, greater_than_or_equal_to: 0, less_than: 120) | |
end | |
end | |
# Some tests that show off assertion failures | |
test "example exception for unknown key" do | |
params = %{"name" => "tyler"} | |
changeset = Person.changeset(%Person{}, params) | |
assert_invalid changeset, :tyler, error_message =~ "hello world" | |
end | |
test "example error message for incorrect assertion" do | |
params = %{"name" => "tyler"} | |
changeset = Person.changeset(%Person{}, params) | |
assert_invalid changeset, :age, error_message =~ "hello world" | |
end | |
test "example error message for valid field" do | |
params = %{"name" => "tyler"} | |
changeset = Person.changeset(%Person{}, params) | |
assert_invalid changeset, :name, error_message =~ "hello world" | |
end | |
test "example error message for valid changeset" do | |
params = %{"name" => "tyler", "age" => 100} | |
changeset = Person.changeset(%Person{}, params) | |
assert_invalid changeset, :age, error_message =~ "hello world" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment