1
0
mirror of https://github.com/danbee/chess synced 2025-03-04 08:39:06 +00:00

Add move and move test

This commit is contained in:
Daniel Barber 2018-05-04 20:07:59 +02:00
parent 6513cdbee0
commit 3c4d5867a3
Signed by: danbarber
GPG Key ID: 931D8112E0103DD8
3 changed files with 127 additions and 0 deletions

31
lib/chess/store/move.ex Normal file
View File

@ -0,0 +1,31 @@
defmodule Chess.Store.Move do
@moduledoc false
use Ecto.Schema
use Timex.Ecto.Timestamps
import Ecto.Changeset
# import Ecto.Query
alias Chess.Store.Game
schema "moves" do
field :from, :map
field :to, :map
field :piece, :map
field :piece_captured, :map
belongs_to :game, Game
timestamps()
end
def changeset(struct, params \\ %{}) do
struct
|> cast(params, required_attrs())
|> validate_required(required_attrs())
end
defp required_attrs, do: ~w[game_id from to piece]a
end

View File

@ -0,0 +1,15 @@
defmodule Chess.Repo.Migrations.CreateMoves do
use Ecto.Migration
def change do
create table(:moves) do
add :game_id, references(:games)
add :from, :map
add :to, :map
add :piece, :map
add :piece_captured, :map
timestamps()
end
end
end

View File

@ -0,0 +1,81 @@
defmodule Chess.MoveTest do
@moduledoc false
use Chess.DataCase
describe "move" do
alias Chess.Repo
alias Chess.Board
alias Chess.Store.Move
import Chess.Factory
test "move is valid with a game, a from, and a to" do
user = insert(:user, %{email: "link@hyrule.com"})
opponent = insert(:user, %{email: "zelda@hyrule.com"})
game = insert(:game, %{
board: Board.default,
user_id: user.id,
opponent_id: opponent.id,
})
changeset = Move.changeset(%Move{}, %{
game_id: game.id,
from: %{file: 4, rank: 1},
to: %{file: 4, rank: 3},
piece: %{"type" => "pawn", "colour" => "white"},
})
assert changeset.valid?
assert {:ok, _move} = Repo.insert(changeset)
end
test "move is invalid without a game" do
changeset = Move.changeset(%Move{}, %{
from: %{file: 4, rank: 1},
to: %{file: 4, rank: 3},
piece: %{"type" => "pawn", "colour" => "white"},
})
refute changeset.valid?
end
test "move is invalid without a from or to" do
user = insert(:user, %{email: "link@hyrule.com"})
opponent = insert(:user, %{email: "zelda@hyrule.com"})
game = insert(:game, %{
board: Board.default,
user_id: user.id,
opponent_id: opponent.id,
})
changeset = Move.changeset(%Move{}, %{
game_id: game.id,
piece: %{"type" => "pawn", "colour" => "white"},
})
refute changeset.valid?
end
test "move is invalid without a piece" do
user = insert(:user, %{email: "link@hyrule.com"})
opponent = insert(:user, %{email: "zelda@hyrule.com"})
game = insert(:game, %{
board: Board.default,
user_id: user.id,
opponent_id: opponent.id,
})
changeset = Move.changeset(%Move{}, %{
game_id: game.id,
from: %{file: 4, rank: 1},
to: %{file: 4, rank: 3},
})
refute changeset.valid?
end
end
end