Hi Everyone!
I am using Elixir for some months now, and I know about pattern matching and all. Right now I’m using the book series (Phoenix inside out) by Shankar Dhanasekaran.
At one step there is the test file called catalog_test.exs
with the following code
defmodule Mango.CatalogTest do
use ExUnit.Case
alias Mango.Catalog
alias Mango.Catalog.Product
test "list_products/0 returns all products" do
[p1, p2] = Catalog.list_products
assert %Product{} = p1
assert p1.name == "Tomato"
assert %Product{} = p2
assert p2.name == "Apple"
end
end
this file tests catalog.ex
which displays two products (structs) as follows
defmodule Mango.Catalog do
alias Mango.Catalog.Product
def list_products do
product1 = %Product{ name: "Tomato", price: 50 }
product2 = %Product{ name: "Apple", price: 100 }
[product1, product2]
end
end
the struct is defined at product.ex
as
defmodule Mango.Catalog.Product do
defstruct [:name, :price]
end
when I run the test as mix test test/mango/catalog/catalog_test.exs
it works fine, which is great, but when I change the following two lines in the test files
assert %Product{} = p1
assert %Product{} = p2
to
assert p1 = %Product{}
assert p2 = %Product{}
it fails and gives the following output, but I was expecting it to pass
warning: variable "p1" is unused
test/mango/catalog/catalog_test.exs:7
warning: variable "p2" is unused
test/mango/catalog/catalog_test.exs:7
1) test list_products/0 returns all products (Mango.CatalogTest)
test/mango/catalog/catalog_test.exs:6
Assertion with == failed
code: assert p1.name() == "Tomato"
left: nil
right: "Tomato"
stacktrace:
test/mango/catalog/catalog_test.exs:10: (test)
Finished in 0.07 seconds
1 test, 1 failure
Randomized with seed 917119
Would somebody please explain why changing code in those two lines that way won’t work?