Phoenix测试数据持续使测试不可重复

时间:2017-01-15 14:30:49

标签: testing elixir phoenix-framework ecto

请注意,这与my forum post重复。

我正在使用Phoenix(1.2.1)并且在测试环境中遇到问题。问题是在测试数据库中插入(更新,删除等)的数据会持久存储在测试数据库中,使我的测试不可重复。

首次运行:

root@d7594ec7baf0:/mnt/sidecar_api# mix test
................................
Finished in 2.2 seconds

32 tests, 0 failures

Randomized with seed 180820

第二次运行:

root@d7594ec7baf0:/mnt/sidecar_api# mix test
...........................

  1) test user signup with POST /v1/users with valid attributes   (SidecarApi.V1.UserControllerTest)
 test/controllers/v1/user_controller_test.exs:15
 Assertion with == failed
 code: response == expected
 lhs:  %{"jsonapi" => %{"version" => "1.0"}, "data" => %{"attributes" => %{"first-name" => "Juan", "last-name" => "Dela Cruz", "primary-email" => "jdelacruz@example.com", "primary-mobile-number" => "639123456789", "username" => "jdelacruz"}, "type" => "user", "id" => "2"}}
 rhs:  %{"jsonapi" => %{"version" => "1.0"}, "data" => %{"attributes" => %{"first-name" => "Juan", "last-name" => "Dela Cruz", "primary-email" => "jdelacruz@example.com", "primary-mobile-number" => "639123456789", "username" => "jdelacruz"}, "type" => "user", "id" => "1"}}
 stacktrace:
   test/controllers/v1/user_controller_test.exs:36: (test)

....

Finished in 2.3 seconds
32 tests, 1 failure

Randomized with seed 556822

这些实例中唯一相关的信息是对象ID。我正在检查插入的记录是否具有ID 1,这是我在执行所有测试之前对DB状态的假设。

这是我的test.exs

use Mix.Config

config :sidecar_api, SidecarApi.Endpoint,
  http: [port: 4001],
  server: false

config :logger, level: :warn

config :sidecar_api, SidecarApi.Repo,
  adapter: Ecto.Adapters.Postgres,
  username: "sidecar",
  password: "sidecardb",
  database: "sidecar_test",
  hostname: "sidecar-db-main",
  pool: Ecto.Adapters.SQL.Sandbox

test_helper.exs

ExUnit.start

Ecto.Adapters.SQL.Sandbox.mode(SidecarApi.Repo, :manual)

请注意,在每次测试之后,检查psql本身的postgres内容是否反映了空数据库。适用于开发和测试环境。现在,我很困惑在哪里看。

sidecar_dev=# select * from users;
 id | username | password | first_name | last_name | inserted_at |     updated_at
----+----------+----------+------------+-----------+-------------+------------
(0 rows)


sidecar_test=# select * from users;
 id | username | password | first_name | last_name | inserted_at | updated_at
----+----------+----------+------------+-----------+-------------+------------
(0 rows)

提前致谢!

1 个答案:

答案 0 :(得分:0)

看起来数据在运行之间被清除,但你的id序列没有被重置。

code: response == expected
  lhs:  %{"jsonapi" => %{"version" => "1.0"}, "data" => %{"attributes" => %{"first-name" => "Juan", "last-name" => "Dela Cruz", "primary-email" => "jdelacruz@example.com", "primary-mobile-number" => "639123456789", "username" => "jdelacruz"}, "type" => "user", "id" => "2"}}
  rhs:  %{"jsonapi" => %{"version" => "1.0"}, "data" => %{"attributes" => %{"first-name" => "Juan", "last-name" => "Dela Cruz", "primary-email" => "jdelacruz@example.com", "primary-mobile-number" => "639123456789", "username" => "jdelacruz"}, "type" => "user", "id" => "1"}}

请注意,ID不同