Skip to content

Instantly share code, notes, and snippets.

@joshchernoff joshchernoff/spec.ex
Last active Jan 12, 2017

Embed
What would you like to do?
An idea of how to write specs.
defmodule Digitalcakes.PostTest do
use Digitalcakes.ModelCase
alias Digitalcakes.Post
import Digitalcakes.Factory
test "changeset with valid attributes" do
changeset = Post.changeset(%Post{}, params_for(:post))
assert changeset.valid?
end
test "changeset validates required attributes" do
error = "can't be blank"
assert has_error_msg?(:title, error)
assert has_error_msg?(:body, error)
assert has_error_msg?(:slug, error)
refute has_error_msg?(:published_at, error)
refute has_error_msg?(:draft, error)
end
test "changeset validates unique constraints" do
insert(:post, slug: "foo")
{_, cs} = Digitalcakes.Repo.insert(Post.changeset(%Post{}, params_for(:post, slug: "foo")))
assert has_error_msg?(:slug, "has already been taken", cs.errors)
end
defp has_error_msg?(symbol, error_msg, errors) do
case errors[symbol] do
{msg, _} ->
msg == error_msg
_ ->
false
end
end
defp has_error_msg?(symbol, error_msg) do
case cs_errors(%{symbol => nil})[symbol] do
{msg, _} ->
msg == error_msg
_ ->
false
end
end
defp cs_errors(model \\ %Digitalcakes.Post{}, params) do
model.__struct__.changeset(model, params).errors
end
end
@joshchernoff

This comment has been minimized.

Copy link
Owner Author

commented Jan 12, 2017

Whoops just found a typo in my spec, fixing but now spec fails.

@joshchernoff

This comment has been minimized.

Copy link
Owner Author

commented Jan 12, 2017

fixed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.