[][src]Macro factori::factori

macro_rules! factori {
    ($($input:tt)*) => { ... };
}

A macro to define a factory for a type.

The macro accepts:

  • The type to be constructed by the factory.

  • A default { } block.

    This provides default values for all fields in the struct.

  • Zero or more mixin name { } blocks.

    These provide values to override the default values of one or more fields. They are typically used to define groups of values which allow you to quickly create test objects which are in certain states.

    Multiple mixin blocks can set the same attributes and the precedence is determined by the order that they are included in calls to create!().

Example

struct Order {
    id: u64,
    shipped: bool,
}

factori!(Order, {
    default {
        id = 1,
        shipped = false,
    }

    mixin shipped {
        shipped = true,
    }
});

fn main() {
    let order = create!(Order, :shipped);
}

Constructing complex types

Under the hood, the example above constructs Vehicle using the struct literal syntax, passing the values defined in the default and mixin blocks.

This isn't always possible, such as for types which can't be constructed with struct literal syntax (enums and tuple structs) or types with private fields. For these more complex types, a builder block can be provided to tell factori!() how to turn the fields in the default and mixin blocks into the factory's type.

When a builder block is provided, the fields in default define an anonymous, temporary struct that is used during factory construction. To achieve this, the types of fields must be provided inside the default block.

pub struct Order(u64, bool);

factori!(Order, {
    default {
        id: u64 = 1,
        shipped: bool = false,
    }

    builder {
        // All fields from default { } are in scope here with their values.
        // We construct a tuple struct here, but we could easily call a
        // method like Order::new().
        Order(id, shipped)
    }

    mixin shipped {
        shipped = true,
    }
});

fn main() {
    let order = create!(Order, :shipped, id: 2);
}