Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert two maps in Phoenix controller testing with pattern matching

In my phoenix controller testing, I am doing something like this,

describe "update/2" do
  setup [:create_user]
  test "Edits, and responds with the user if attributes are valid", %{conn: conn, user: user} do

    response = 
      conn
      |> put(user_path(conn, :update, user.id, @update_attrs))
      |> json_response(200)

    expected = %{
      "data" => 
        %{"currentCity" => "pune", "mobileNumber" => "1234567890"}        
      }

  assert expected == response  

end

And my response map is

%{
  "data" => %{"currentCity" => "pune",
              "mobileNumber" => "1234567890",
              "name" => "xyz",
              "gender" => "male"}}

Since my response map contains extra keys which is not present in expected map, so the assertion with == fails, so I am trying to do assertion with patter matching like this

assert expected = response

but In this case assertion is always true no matter what the are the values in expected and response.

I am confused what's happening with the pattern matching in the case of maps.

like image 451
chandradot99 Avatar asked Aug 17 '26 17:08

chandradot99


2 Answers

I am confused what's happening with the pattern matching in the case of maps.

When you pattern match, the pattern must be present on the left hand side. You cannot "store" a pattern. What you're doing here is matching the pattern expected with the value of response, which will always match because the expected is a variable which will match any value on the right hand side.

To fix this, you can just inline the pattern like this:

assert %{"data" => 
  %{"currentCity" => "pune", "mobileNumber" => "1234567890"}        
} = response
like image 158
Dogbert Avatar answered Aug 19 '26 16:08

Dogbert


One could check the values of interest explicitly:

with %{"data" => 
       %{"currentCity" => pune,
         "mobileNumber" => number}} <- response do
  assert pune == "pune"
  assert number == "1234567890"
else
  _ -> assert false
end 
like image 25
Aleksei Matiushkin Avatar answered Aug 19 '26 16:08

Aleksei Matiushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!