Search code examples
elixirex-unit

ExUnit triggers Empty Error with setup_all block


I have a test which requires preinserted data.

So I am trying to setup those data with setup_all callback as those data can be setup once.

Since I do not want to assign anything to context, I defined setup_all like below

setup_all do
  create_languages() 
  create_regions()
  create_currencies() 
  create_user()
  :ok
end

And each test has a function, which gets one struct from data created.

For example, one of tests is like below:

test "update_core/2 (region_id) with valid data, updates core" do
  region = get_region()
  core = create_core()

  {:ok, core} = Cores.update_core(core, %{region_id: region.id})

  assert region.id == core.region_id
end

However, region = get_region() triggers an empty error. Why can this function get struct? IO.inspect shows create_regions() actually create multiple regions. Am I missing something here?

Thank you in advance.


Solution

  • There's a good chance that Ecto has either been configured to be used in sandbox mode or set to reset the database after every test, in your :test environment. So you should use setup block instead of setup_all:

    setup do
      create_languages() 
      create_regions()
      create_currencies() 
      create_user()
      :ok
    end
    

    The setup block is called before every test, while setup_all is only called once.