0

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.

Sheharyar
  • 73,588
  • 21
  • 168
  • 215
D.R
  • 829
  • 4
  • 16
  • 30

1 Answers1

1

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.

Sheharyar
  • 73,588
  • 21
  • 168
  • 215
  • The reason why I want to use `setup_all` rather than `setup` is that since `setup` calls for each individual test so it takes long time to do... – D.R Oct 26 '18 at 10:12
  • Yes, but that's the proper way to go, so different tests don't interfere with each other. To speed up tests, you can make sure that Ecto is indeed set up in Sandbox mode, and [run them concurrently](https://hexdocs.pm/ecto/Ecto.Adapters.SQL.Sandbox.html) by setting the `async` tag to true. – Sheharyar Oct 26 '18 at 10:15