pinksynth

pinksynth

Tip: Using Ecto transactions in tests

Whenever tests have to interact with an Ecto.Repo, sometimes it’s necessary to test a few different branches or paths that data can take. This can be tedious with a database and may result in “resetting” records so they may be re-tested. Here’s a crude example of “resetting” some data to continue with a test:

test "vaccinate_dog/1 vaccinates dog and creates vax record with the corresponding name" do
  dog = dog_fixture()
  
  # Perform assertions about vaccinations
  assert :ok = vaccinate_dog(dog, "bordetella")
  assert %{id: dog_id, vaccinated: true} = dog = Repo.one!(Dog)
  assert %{dog_id: ^dog_id, type: "bordetella"} = Repo.one!(Vax)

  # Reset state for the dog
  Repo.delete_all(Vax)
  dog |> Ecto.Changeset.change(%{vaccinated: false}) |> Repo.update!()

  # Performmore  assertions about vaccinations
  assert :ok = vaccinate_dog(dog, "rabies")
  assert %{id: dog_id, vaccinated: true} = dog = Repo.one!(Dog)
  assert %{dog_id: ^dog_id, type: "rabies"} = Repo.one!(Vax)
end

By using Repo.transaction/2, it’s easy to simply roll back a transaction rather than “resetting” anything (assuming that side-effects are not a concern for the purposes of the test.

test "vaccinate_dog/1 vaccinates dog and creates vax record with the corresponding name" do
  dog = dog_fixture()

  for vaccine <- ["rabies", "bordetella"] do
    in_transaction(fn ->
      assert :ok = vaccinate_dog(dog, vaccine)
      assert %{id: dog_id, vaccinated: true} = dog = Repo.one!(Dog)
      assert %{dog_id: ^dog_id, type: vaccine} = Repo.one!(Vax)
    end)
  end
  
  defp in_transaction(fun) when is_function(fun, 0) do
    Repo.transaction(fn ->
      fun.()
      Repo.rollback(:ok)
    end)
  end
end

I know that it’s generally best to decouple the DB and the business logic as much as possible, but I have found this to be a useful way to succinctly cover more ground within Repo-related tests.

Most Liked

al2o3cr

al2o3cr

This is usually where I’d stop this test and write another one, TBH. Unless dog_fixture is very expensive to compute, I’d prefer to see duplication if testing with "rabies" vs "bordetella" exposes different behavior.

Also note there’s no support AFAIK for nested transactions, so this won’t work as expected if used with the sandbox-enabled test harness that’s generated by Phoenix.

Where Next?

Popular in Guides/Tuts Top

smpallen99
Did you know that IO.inspect/2 returns the the first argument and accepts a label option as a second argument. This makes it a perfect to...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
f0rest8
Hi, TLDR: form attribute set on the input fields and button submit. I just wanted to share a solution I discovered when making live inl...
New
benwilson512
Correct if me I’m wrong, as best I can tell there aren’t any reasons to use mix run --no-halt in production vs releases. The marginal val...
New
dkuhlman
For those of you who might be interested in using ZeroMQ in Elixir, I converted the Erlang examples in the ZeroMQ “zguide” to Elixir. I ...
New
dogweather
I just finished a long process of configuring and debugging a Docker Compose-based dev environment. Several late-night hours! I think I’v...
New
thetechnologyvault
One of our team members just published this getting started guide for Elixir/Phoenix devs to use the Nanobox platform: https://content.n...
New
zookzook
If you want to use the MongoDB in your next Killer-App-Project, but you did not dare ask because otherwise many would advise you to use P...
New
mudasobwa
The post covering how to generate nifty types to use in @spec in compile time with macros. https://rocket-science.ru/hacking/2020/07/15/...
New
AstonJ
..or as and when you can think of one :icon_cool: This thread my also be of interest: What took you way too long to figure out? :003:
New

Other popular topics Top

chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New

We're in Beta

About us Mission Statement