Using test fixtures to seed the database in Phoenix
While working on a Phoenix project, I wanted to reuse some of the existing fixtures from my tests to seed the database during development. But importing and calling any of the functions in
seeds.exs throws an error.
The problem #
In a standard Phoenix project,
iex will run in development mode (ie. with
MIX_ENV=dev) and only compile files inside the
So trying to import fixtures that are located in the
/test/support/fixtures directory will not work, even when using an import statement:
Running the code throws this error:
Solution A: Require the file manually #
We can include the file at the top of our file using
The function is now available in our module:
You can pass
__DIR__ as the second argument to
Code.require_file/2, if you want to use a relative import path.
Solution B: Configure Mix to compile all files #
If you need to reference a lot of fixtures or functions from your
/test directory, it might be easier to make them all available at once.
mix.exs file at the root of your project defines the configuration for Mix. One of the variables is called
elixirc_paths, which tells Elixir which directories to include during compilation.
In a default Phoenix project that variable is set by the private
elixirc_paths/1 function, defined further down in the same file.
We can add an extra function clause for the argument
:dev and add the
test/support path to the list of paths the get compiled.
Now all the fixtures and other helper functions from the
test/support/ directory are available in the rest of our Phoenix project (in development mode).