雨伞应用测试中的Ecto.ConstraintError

时间:2018-12-09 21:08:57

标签: testing elixir ecto ex-unit umbrella

我有两个应用程序,用户和播放列表。当应用程序正常运行时,我在配置测试环境时遇到了麻烦

setup do
    :ok = Ecto.Adapters.SQL.Sandbox.checkout(Playlists.Repo)
    Ecto.Adapters.SQL.Sandbox.checkout(Accounts.Repo)
    Ecto.Adapters.SQL.Sandbox.mode(Playlists.Repo, {:shared, self()})
    Ecto.Adapters.SQL.Sandbox.mode(Accounts.Repo, {:shared, self()})         
    :ok
end

test "create a playlist" do
  { _, user1 } = Users.register("user1", "user1@email.com", "user1pw")
  { _, playlist1 } = Playlists.create_playlist("title", "user1")

  assert playlist1 == Playlists.get_playlist!(1)
end

我遇到了这个错误

  1) test Playlist create a playlist (PlaylistsTest)
 test/playlists_test.exs:14
 ** (Ecto.ConstraintError) constraint error when attempting to insert struct:

     * playlists_user_id_fkey (foreign_key_constraint)

 If you would like to stop this constraint violation from raising an
 exception and instead add it as an error to your changeset, please
 call `foreign_key_constraint/3` on your changeset with the constraint
 `:name` as an option.

 The changeset has not defined any constraint.

 code: { _, playlist1 } = Playlists.api_create_playlist("title", "icon", false, "user1")
 stacktrace:
   (ecto) lib/ecto/repo/schema.ex:647: anonymous fn/4 in Ecto.Repo.Schema.constraints_to_errors/3
   (elixir) lib/enum.ex:1314: Enum."-map/2-lists^map/1-0-"/2
   (ecto) lib/ecto/repo/schema.ex:632: Ecto.Repo.Schema.constraints_to_errors/3
   (ecto) lib/ecto/repo/schema.ex:238: anonymous fn/15 in Ecto.Repo.Schema.do_insert/3
   (ecto) lib/ecto/repo/schema.ex:875: anonymous fn/3 in Ecto.Repo.Schema.wrap_in_transaction/6
   (ecto_sql) lib/ecto/adapters/sql.ex:782: anonymous fn/3 in Ecto.Adapters.SQL.checkout_or_transaction/4
   (db_connection) lib/db_connection.ex:1341: DBConnection.run_transaction/4
   test/playlists_test.exs:16: (test)

我检查了正在创建的user1,所以问题一定是在创建播放列表时,并且从错误消息中特别针对唯一约束。在我的仓库迁移的def change()中,我有

create table(:playlists) do
  add :title, :string
  add :user_id, references(:users, null: false)

  timestamps()
end

create unique_index(:playlists, [:title, :user_id])
create unique_index(:playlists_users, [:playlist_id, :user_id])

我弄乱了一些Ecto Sandbox配置,但似乎不起作用。我想念什么?任何帮助表示赞赏。

0 个答案:

没有答案