{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/testing-with-elixir-and-phoenix-models","result":{"data":{"mdx":{"body":"function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n/* @jsx mdx */\nvar _frontmatter = {\n  \"title\": \"Testing with Elixir and Phoenix: Models\",\n  \"order\": 40,\n  \"free\": false,\n  \"active\": true,\n  \"tech\": [\"phoenix\", \"elixir\"]\n};\n\nvar makeShortcode = function makeShortcode(name) {\n  return function MDXDefaultShortcode(props) {\n    console.warn(\"Component \" + name + \" was not imported, exported, or provided by MDXProvider as global scope\");\n    return mdx(\"div\", props);\n  };\n};\n\nvar layoutProps = {\n  _frontmatter: _frontmatter\n};\nvar MDXLayout = \"wrapper\";\nreturn function MDXContent(_ref) {\n  var components = _ref.components,\n      props = _objectWithoutProperties(_ref, [\"components\"]);\n\n  return mdx(MDXLayout, _extends({}, layoutProps, props, {\n    components: components,\n    mdxType: \"MDXLayout\"\n  }), mdx(\"h1\", null, \"Testing with Elixir and Phoenix: Models\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Write tests for User model\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Write tests for Message model\")), mdx(\"p\", null, \"The tests we're going to write for our models are a little bit more specific than the ones we wrote for our controllers and channels. This is because we may call Model behaviors in our Controllers or Channels but not the other way around.\"), mdx(\"p\", null, \"So we need to test our input data validations and our custom queries.\"), mdx(\"p\", null, \"Channel/Controller tests often indirectly test the behavior of our model, like when we get initial messages on \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"channel.join\"), \" and expect \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"latest_room_messages/2\"), \" to have been called with the most recent 10 messages. But we also want to make sure that our models work independently of our controllers and channels. Fortunately these tests are simpler than the Controller/Channel tests since we can call the functions directly (e.g. \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"User.changeset/2\"), \") rather than simulating an HTTP request like we had to do with our Controller.\"), mdx(\"h2\", null, \"User model\"), mdx(\"p\", null, \"We start by importing \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"ModelCase\"), \", which contains useful functions for \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Model\"), \" testing. Check them out at \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"test/support/model_case.ex\"), \". Then, just as we did in our other tests, we create a set of valid and invalid attributes to make our tests easier to read.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.UserTest do\\n  use PhoenixChat.ModelCase\\n\\n  alias PhoenixChat.User\\n\\n  @valid_attrs %{email: \\\"foo@bar.com\\\", encrypted_password: \\\"some content\\\", username: \\\"some content\\\"}\\n  @invalid_attrs %{}\\n\\n  ...\\nend\\n\")), mdx(\"p\", null, \"Since we don't have any custom queries for our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"User\"), \" model yet, all we're going to test is our validations on input data. The first and simplest is testing our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"changeset\"), \" with valid inputs. To do this we use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"changeset.valid?\"), \", which is a field in the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Ecto.Changeset\"), \" struct \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/ecto/Ecto.Changeset.html\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \". If you log a valid changeset, you'll get something like the result below (note the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"valid?: true\"), \" field).\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"#Ecto.Changeset<action: nil, changes: %{email: \\\"foo@bar.com\\\", username: \\\"some content\\\"}, errors: [], data: #PhoenixChat.User<>, valid?: true>\\n\")), mdx(\"p\", null, \"This should be the same as the output from the generator.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"test \\\"changeset with valid attributes\\\" do\\n  changeset = User.changeset(%User{}, @valid_attrs)\\n  assert changeset.valid?\\nend\\n\")), mdx(\"p\", null, \"Then we're going to test all the ways in which we can make an invalid \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"changeset\"), \". Cure\"), mdx(\"p\", null, \"If you look at our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"changeset\"), \" in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"web/models/user.ex\"), \", you'll see that we have a few constraints: namely \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"cast\"), \", \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"validate_format\"), \", \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"validate_length\"), \", and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"unique_constraint\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"def changeset(model, params \\\\\\\\ :empty) do\\n  model\\n  |> cast(params, ~w(email username), [])\\n  |> validate_format(:email, ~r/@/)\\n  |> validate_length(:username, min: 1, max: 20)\\n  |> update_change(:email, &String.downcase/1)\\n  |> unique_constraint(:email)\\n  |> update_change(:username, &String.downcase/1)\\n  |> unique_constraint(:username)\\nend\\n\")), mdx(\"p\", null, \"In each of the following tests, we're going to create a changeset with invalid attributes of a particular type and check the error message to make sure it's the error we expect.\"), mdx(\"p\", null, mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"changeset\"), \" stores errors in its \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":errors\"), \" field, which is populated by a list of two-element tuples in the format \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"{field_name, error_msg}\"), \". So in our assertion, we're pulling out the value we want using \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"in\"), \" to pull the value out of the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"errors\"), \" list. We encourage you to put in the occasional \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"IO.puts\"), \" to make sure you understand which values are coming from where.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"test \\\"changeset with blank email and username\\\" do\\n  %{errors: errors} = User.changeset(%User{}, %{})\\n  assert {:email, {\\\"can't be blank\\\", []}} in errors\\n  assert {:username, {\\\"can't be blank\\\", []}} in errors\\nend\\n\\ntest \\\"changeset with invalid email format\\\" do\\n  %{errors: errors} = User.changeset(%User{}, %{email: \\\"foo\\\"})\\n  assert {:email, {\\\"has invalid format\\\", []}} in errors\\nend\\n\\ntest \\\"changeset with username invalid length\\\" do\\n  long_username = String.duplicate \\\"f\\\", 21\\n  %{errors: errors} = User.changeset(%User{}, %{username: long_username})\\n  assert {:username, {\\\"should be at most %{count} character(s)\\\", [count: 20]}} in errors\\nend\\n\\ntest \\\"changeset must have a unique email\\\" do\\n  changeset = User.changeset(%User{}, @valid_attrs)\\n  Repo.insert!(changeset)\\n\\n  changeset = User.changeset(%User{}, @valid_attrs)\\n  {:error, changeset} = Repo.insert(changeset)\\n  assert {:email, {\\\"has already been taken\\\", []}} in changeset.errors\\nend\\n\\ntest \\\"changeset must have a unique username\\\" do\\n  changeset = User.changeset(%User{}, @valid_attrs)\\n  Repo.insert!(changeset)\\n\\n  attrs = Map.put(@valid_attrs, :email, \\\"test@bar.com\\\")\\n  changeset = User.changeset(%User{}, attrs)\\n  {:error, changeset} = Repo.insert(changeset)\\n  assert {:username, {\\\"has already been taken\\\", []}} in changeset.errors\\nend\\n\")), mdx(\"p\", null, \"Then we need to test our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"registration_changeset\"), \" in the same way. First we pass valid attributes and make sure it works. We're also testing to make sure that an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"encrypted_password\"), \" field was created by using the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"get_change/3\"), \" method \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/ecto/Ecto.Changeset.html#get_change/3\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \". We don't need to test \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"put_encrypted_pw/1\"), \" directly because it is safe to assume that \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Comeonin\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Bcrypt\"), \" work properly.\"), mdx(\"p\", null, \"Once we've tested a passing changeset, we send a password that is too short and ensure that our error corresponds to the \\\"password is too short\\\" error.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"test \\\"registration changeset with valid attributes\\\" do\\n  valid_attrs = Map.put(@valid_attrs, :password, \\\"password\\\")\\n  changeset = User.registration_changeset(%User{}, valid_attrs)\\n  assert changeset.valid?\\n  assert get_change(changeset, :encrypted_password)\\nend\\n\\ntest \\\"registration changeset with invalid password length\\\" do\\n  long_password = String.duplicate \\\"p\\\", 101\\n  %{errors: errors} = User.registration_changeset(%User{}, %{password: long_password})\\n  assert {:password, {\\\"should be at most %{count} character(s)\\\", [count: 100]}} in errors\\nend\\n\")), mdx(\"h2\", null, \"Message model\"), mdx(\"p\", null, \"Our message model is a little bit more complicated since we need to test our custom query that fetches the latest 10 posts.\"), mdx(\"p\", null, \"First we set up the valid and invalid attributes.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.MessageTest do\\n  use PhoenixChat.ModelCase\\n\\n  alias PhoenixChat.Message\\n\\n  @valid_attrs %{body: \\\"some content\\\", room: \\\"some content\\\", timestamp: \\\"2010-04-17 14:00:00\\\"}\\n  @invalid_attrs %{}\\n\\n  ...\\nend\\n\")), mdx(\"p\", null, \"Then we test our changeset with those attributes, just as we did with the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"User\"), \" model.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"test \\\"changeset with valid attributes\\\" do\\n  changeset = Message.changeset(%Message{}, @valid_attrs)\\n  assert changeset.valid?\\nend\\n\\ntest \\\"changeset with invalid attributes\\\" do\\n  %{errors: errors} = Message.changeset(%Message{}, @invalid_attrs)\\n  assert {:body, {\\\"can't be blank\\\", []}} in errors\\n  assert {:timestamp, {\\\"can't be blank\\\", []}} in errors\\n  assert {:room, {\\\"can't be blank\\\", []}} in errors\\nend\\n\")), mdx(\"p\", null, \"And now we test our query. We can test queries by running them and then checking the records returned by the query and matching them with the results that we expect.\"), mdx(\"p\", null, \"In some circumstances, we may choose to run an assertion on the query struct returned by \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Ecto\"), \". We're going to do this in the last assertion of this test because all we're testing is that the default \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"limit\"), \" is set to 10. You could also test this by creating 11 messages, running the query, then assert that we only got 10 back.\"), mdx(\"p\", null, \"We prepare the test by inserting multiple messages to the database with different timestamps, since we need to know which are the most recent to ensure they are properly ordered.\"), mdx(\"p\", null, \"Then we create our query by calling \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"latest_room_messages/2\"), \" with \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"1\"), \" as the room (note that we added three messages to room 1) and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"2\"), \" as the override for the default value of \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"10\"), \", so we will only get the two most recent messages back. Now that we've created the query we want, we use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Repo.all/1\"), \" to get the result of the query.\"), mdx(\"p\", null, \"Now we run our first assertion, which makes sure that we only received 2 messages. If we hadn't specified \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"2\"), \" in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"latest_room_messages/2\"), \", we should have received all 3 messages we added to the database because the default limit is 10 messages.\"), mdx(\"p\", null, \"From there we use the \", mdx(\"a\", {\n    \"href\": \"http://elixir-lang.org/getting-started/pattern-matching.html#pattern-matching\",\n    \"parentName\": \"p\"\n  }, \"head-tail pattern matching\"), \" to separate out the first message from the list (the head) from the rest of the message (the tail) and assign the head to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"msg1\"), \" and the tail to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"msg2\"), \".\"), mdx(\"p\", null, \"Then in our assertion, we are checking to make sure that the second message (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"msg2\"), \") has the same timestamp value as the second message we added to our database (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"second\"), \"). We do this with \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/ecto/Ecto.DateTime.html#compare/2\",\n    \"parentName\": \"p\"\n  }, \"Ecto.DateTime.compare/2\"), \". Keep in mind that comparing Ecto.DateTime structs with things like \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \">\"), \" or other comparison operators won't work as expected because they're treated as structs rather than normal values.\"), mdx(\"p\", null, \"Our next assertion checks to make sure that the values we received are ordered properly. We expect that our most recent (by timestamp) message should be first, so we use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"compare/2\"), \" again to assert that \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"msg1.timestamp\"), \" is greater than (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":gt\"), \") \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"msg2.timestamp\"), \".\"), mdx(\"p\", null, \"The last assertion, as mentioned earlier, tests to make sure that the default value for our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"limit\"), \" is 10 if we do not specify anything.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"test \\\"query that returns latest messages of a given room\\\" do\\n  first  = Ecto.DateTime.from_erl({{2016, 5, 23}, {12, 30, 12}})\\n  second = Ecto.DateTime.from_erl({{2016, 5, 24}, {12, 30, 12}})\\n  third  = Ecto.DateTime.from_erl({{2016, 5, 25}, {12, 30, 12}})\\n  Repo.insert!(%Message{room: \\\"1\\\", body: \\\"test\\\", timestamp: first})\\n  Repo.insert!(%Message{room: \\\"1\\\", body: \\\"test\\\", timestamp: second})\\n  Repo.insert!(%Message{room: \\\"1\\\", body: \\\"test\\\", timestamp: third})\\n  Repo.insert!(%Message{room: \\\"2\\\", body: \\\"test\\\", timestamp: Ecto.DateTime.utc()})\\n\\n  messages = Message.latest_room_messages(\\\"1\\\", 2) |> Repo.all\\n  assert length(messages) == 2\\n\\n  [msg1 | [msg2]] = messages\\n  assert Ecto.DateTime.compare(msg2.timestamp, second) == :eq\\n  assert Ecto.DateTime.compare(msg1.timestamp, msg2.timestamp) == :gt\\n  assert {10, :integer} in Message.latest_room_messages(\\\"1\\\").limit.params\\nend\\n\")), mdx(\"p\", null, \"If you run your tests and you're getting an error along the lines of the code below, you are most likely running the wrong version of Ecto. You need to upgrade to Ecto 2.0.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"3) test changeset with invalid attributes (PhoenixChat.MessageTest)\\n   test/models/message_test.exs:14\\n   Assertion with in failed\\n   code: {:body, \\\"can't be blank\\\"} in errors\\n   lhs:  {:body, \\\"can't be blank\\\"}\\n   rhs:  [body: {\\\"can't be blank\\\", []}, timestamp: {\\\"can't be blank\\\", []},\\n          room: {\\\"can't be blank\\\", []}]\\n   stacktrace:\\n     test/models/message_test.exs:16: (test)\\n\")));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Testing with Elixir and Phoenix: Models Write tests for User model Write tests for Message model The tests we're going to write for our…","frontmatter":{"title":"Testing with Elixir and Phoenix: Models","order":40,"active":true,"free":false,"tech":["phoenix","elixir"]}}},"pageContext":{"slug":"testing-with-elixir-and-phoenix-models","prevNode":{"frontmatter":{"title":"Testing with Elixir and Phoenix: Channels","active":true,"free":false,"order":39,"tech":["phoenix","elixir"]},"fields":{"slug":"testing-with-elixir-and-phoenix-channels"}},"nextNode":{"frontmatter":{"title":"Associate Organizations and Users","active":true,"free":false,"order":41,"tech":["phoenix"]},"fields":{"slug":"associate-organizations-and-users"}}}},"staticQueryHashes":["1723017916"]}