Last active
September 7, 2015 16:25
-
-
Save Gazler/21ab4192eebfbf23bd1b 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
def show | |
case Car.create(conn.assigns.user, params) do | |
{:ok, car} -> | |
conn | |
|> redirect(to: car) | |
{:error, changeset} -> | |
conn | |
|> render("new.html", changeset: changeset) | |
end | |
end |
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 CarControllerTest do | |
use MyAppConnCase | |
@valid_attrs %{name: "Some Car"} | |
@invalid_attrs %{name: ""} | |
setup do | |
user = User.create(%{name: "Some User}) | |
{:ok, user: user} | |
end | |
test "creates resource and redirects when data is valid", %{user: user} do | |
conn = post conn(), user_car_path(conn, :create, user), car: @valid_attrs | |
assert redirected_to(conn) == car_path(conn, :index) | |
car = Repo.get_by(car, @valid_attrs) | |
assert car.name == "Some car" | |
assert car.user_id == user.id | |
assert get_flash(conn, :info) == "Car created successfully." | |
end | |
test "does not create resource and renders errors when data is invalid", %{user: user} do | |
conn = post conn(), user_car_path(conn, :create, user), car: @invalid_attrs | |
assert html_response(conn, 200) =~ "New car" | |
assert html_response(conn, 200) =~ "Name can't be blank" | |
end | |
test "redirects when the user does not exist" do | |
conn = post conn(), user_car_path(conn, :create, -1), car: @invalid_attrs | |
assert redirected_to(conn) == user_path(conn, :index) | |
assert get_flash(conn, :error) == "User not found" | |
end | |
end | |
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 Car do | |
... | |
def create(%User{} = user, params) do | |
build(user, :cars) | |
|> Car.changeset(params) | |
|> Repo.insert | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment