Refine tests and foreign key constraints around transactions.block_id

pull/2/head
Doc Ritezel 7 years ago
parent 5035aac6eb
commit de9952ae4d
  1. 11
      lib/explorer/transaction.ex
  2. 12
      test/explorer/transaction_test.exs

@ -15,11 +15,14 @@ defmodule Explorer.Transaction do
belongs_to :block, Explorer.Block
end
@required_attrs ~w(hash)a
@optional_attrs ~w()a
@doc false
def changeset(%Transaction{} = block, attrs) do
block
|> cast(attrs, [:block_id, :hash])
|> validate_required([:block_id, :hash])
def changeset(%Transaction{} = transaction, attrs \\ :empty) do
transaction
|> cast(attrs, [:block_id | @required_attrs], @optional_attrs)
|> validate_required(@required_attrs)
|> foreign_key_constraint(:block_id)
|> update_change(:hash, &String.downcase/1)
|> unique_constraint(:hash)

@ -6,19 +6,19 @@ defmodule Explorer.TransactionTest do
describe "changeset/2" do
test "with valid attributes" do
block = insert(:block)
changeset = Transaction.changeset(%Transaction{}, %{block_id: block.id, hash: "0x0"})
assert(changeset.valid?)
changeset = Transaction.changeset(%Transaction{}, %{hash: "0x0", block_id: block.id})
assert changeset.valid?
end
test "with an invalid block" do
{:error, changeset} = Transaction.changeset(%Transaction{}, %{block_id: 0, hash: "0x0"}) |> Repo.insert
assert changeset.errors == [block_id: {"does not exist", []}]
test "with a block that does not exist in the database" do
{:error, changeset} = Transaction.changeset(%Transaction{}, %{hash: "0x0", block_id: 0}) |> Repo.insert
refute changeset.valid?
assert [block_id: {"does not exist", []}] = changeset.errors
end
test "with invalid attributes" do
changeset = Transaction.changeset(%Transaction{}, %{racecar: "yellow ham"})
refute(changeset.valid?)
refute changeset.valid?
end
end
end

Loading…
Cancel
Save