View Source Myrmidex.Factory behaviour (myrmidex v0.3.0)

Defines a behaviour and utility for associating GeneratorSchemas with a datasource. Typically used in your test support files as the definitive source for creating streams that make sense within your domain: i.e. your schemas.

Opts based to this module via use are persisted at compile time and will be passed to, e.g. Myrmidex.to_stream/2, in order to delegate to your domain-specific generator schema. This module itself uses Myrmidex.GeneratorSchema, so you may define all, or factory-specific, casts within the factory module, or fallback on any generator schema.

Runtime opts passed in the second argument to to_stream/2 or attrs/2 will override these module-specific compile-time opts.

Putting this all together, a basic implmentation could look something like:

# test/support/factory.ex

defmodule MyApp.Support.Factory do
  use Myrmidex.Factory

  # Your factory api is up to you, but one option is to define streams
  # that can then be composed together before calling `persist/3`.
  def my_schema_stream(overrides \ [], stream_opts \ []) do
    %MySchema{}
    |> Myrmidex.affix(overrides)
    |> to_stream(stream_opts)
  end

  @impl Myrmidex.Factory
  def insert(_module, [attrs]) do
    # Handle insert_one.
    # This is the place to invoke your changeset functions.
  end

  def insert(_module, attrs) when is_list(attrs) do
    # Handle insert_all.
  end

  @impl Myrmidex.GeneratorSchema
  def cast_field({_field, _type}, _opts) do
    # Handle and data-source specific casts: e.g. uuids, etc.
  end

  generator_schema_fallback(Myrmidex.GeneratorSchemas.Default)
end

Your setup functions might then look like:

# test/support/setup.ex

alias MyApp.Support.Factory

def seed_my_schema(context \ %{}) do
  context
  |> # do anything with context
  |> Factory.my_schema_stream(overrides)
  |> Factory.persist()
end

Delaying the enumeration of streams leaves your factory functions very composable, and useful throughout your app, during testing and development.

Summary

Callbacks

Callback to insert one or many into a store

Callbacks

Link to this callback

insert(struct_mod, attrs)

View Source (optional)
@callback insert(struct_mod :: module(), attrs :: term() | [term()]) :: any()

Callback to insert one or many into a store