Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phoenix test suite can't find column when running test

I'm building my first phoenix test. I'm just trying to assert that there is content on the screen. I'm using ex_machina for a factory, that may be my problem but I'm not sure? Here is my code.

Table:

create table(:locations) do
  add :start,  :string
  add :finish, :string
end

Test:

defmodule AwesomeLunch.LocationsControllerTest do
  use AwesomeLunch.ConnCase

  import AwesomeLunch.Factory

  test "shows start and finish for locations" do
    conn = conn()
    locations = insert(:locations)

    conn = get conn, locations_path(conn, :show, locations.id)

    assert html_response(conn, 200) =~ locations.start
  end
end

Controller:

def show(conn, %{"id" => locations_id}) do
  locations = Repo.get!(Locations, locations_id)

  render conn, "show.html", locations: locations
end

Error:

** (Postgrex.Error) ERROR (undefined_column): column "finish" of relation "locations" does not exist
 stacktrace:
   (ecto) lib/ecto/adapters/sql.ex:463: Ecto.Adapters.SQL.struct/6
   (ecto) lib/ecto/repo/schema.ex:397: Ecto.Repo.Schema.apply/4
   (ecto) lib/ecto/repo/schema.ex:193: anonymous fn/11 in Ecto.Repo.Schema.do_insert/4
   (ecto) lib/ecto/repo/schema.ex:124: Ecto.Repo.Schema.insert!/4
   test/controllers/locations_controller_test.exs:8: (test)
like image 273
Bitwise Avatar asked Dec 03 '16 20:12

Bitwise


1 Answers

Running mix test runs the migrations.

Here is possibly what happened:

  1. You created a migration file with mix ecto.gen.migration.
  2. You ran mix test. At this point, all migration were run, including your newly created one. This new migration was set as run in the schema_migrations table of your test db.
  3. You edited your migration with an instruction to add a table.
  4. You ran the mix test again: at this point mix saw no new migration to run, as the new one was already set as run. Your new column was never added.

If this is your case, just run MIX_ENV=test mix ecto.reset and all migration will be re-run. (data will also be lost, which shouldn't be a problem for a test db).

===

Tip : you can understand why migrations are run by looking at your mix.exs file in the aliases private function :

  defp aliases do
    [...
     "test": ["ecto.create --quiet", "ecto.migrate", "test"]]
  end
like image 108
AlexHv Avatar answered Oct 23 '22 16:10

AlexHv