Last active
July 19, 2022 17:53
-
-
Save lcmen/de29df5aaf010ac4f365418b13ce7028 to your computer and use it in GitHub Desktop.
Task.async vs Kernel.spawn with async tests using manual sandbox mode in Ecto.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule ScratchApp.UserTest do | |
use ExUnit.Case, async: true | |
alias ScratchApp.{Repo,User} | |
setup do | |
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Repo) | |
end | |
test "it should fail and it does indeed" do | |
pid = self() | |
spawn(fn -> | |
# To fix this test, uncomment the line below | |
# Ecto.Adapters.SQL.Sandbox.allow(Repo, pid, self()) | |
user = Repo.insert!(%User{name: "Homer Simpson", age: 15}) | |
send(pid, user.id) | |
end) | |
receive do | |
id -> assert Repo.get(User, id).age == 15 | |
after | |
100 -> assert false | |
end | |
end | |
test "it should fail but it does not" do | |
task = Task.async(fn -> | |
# It should raise DBConnection.OwnershipError exception that it cannot find ownership process for | |
user = Repo.insert!(%User{name: "Homer Simpson", age: 15}) | |
user.id | |
end) | |
res = Task.await(task) | |
assert Repo.get(User, res).age == 15 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment