[英]How to clean data in every test case in Phoenix
如果第二个测试用例在第一个测试用例之后运行,则它将失败,因为数据库具有在第一个测试用例中创建的ReservationInfo条目。
defmodule MyProj.TestABC do
use ExUnit.Case
alias MyProj.Models.ReservationInfo
alias MyProj.Repo
test "Create Coordinates" do
reservation_result = ReservationInfo.create(["00.00", "00.01"])
assert reservation_result == [{"00.00", :created}, {"00.01", :created}]
end
test "Shouldn't have above created coordinates as it's different test case" do
assert [] == ReservationInfo.get_all()
end
end
我想在运行新的测试用例之前截断所有数据,就像Django为每个测试用例清除数据一样。
您可以使用setup定义一个案例,以在每个测试之前运行一个回调。
def clean_test_data(context) do
# perform setup
:ok
end
setup :clean_test_data
在您的test.exs
配置中,为您的test.exs
添加一个沙箱池:
config :your_app, YourApp.Repo,
adapter: Ecto.Adapters.Postgres,
database: "yourapp_test",
username: "username",
password: "password",
hostname: "localhost",
pool: Ecto.Adapters.SQL.Sandbox
在您的测试文件中有一个设置块:
setup do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(YourApp.Repo)
end
然后,在运行测试时,请使用MIX_ENV=test
环境:
MIX_ENV=test mix test
由于您使用的是Phoenix,因此在test/support/data_case.ex
了一个漂亮的助手来为您管理。
假定该帮助程序用于需要访问数据层的测试中,因此它将在其自己的数据库事务中运行每个测试块,并在测试完成时回滚该事务。
只需更换ExUnit.Case
与TestABC.DataCase
,你应该是好去。 注意:通常不希望使用:async模式,因为在测试运行时可能会产生副作用和死锁。
除了phoenix指南的实现以外,这里还有一些其他文档: https : //hexdocs.pm/phoenix/testing_schemas.html#test-driving-a-changeset 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.