A library that generates random parameters for Ash resource actions. It provides a convenient way to create random test data for your Ash resources by automatically generating random values for accepts and arguments.
Add the random_params DSL to your Ash resource:
defmodulePostdouseAsh.Resource,extensions: [AshRandomParams]attributesdouuid_primary_key:idattribute:author,:string,allow_nil?: falseattribute:title,:string,allow_nil?: falseattribute:content,:string,allow_nil?: trueattribute:tag,:string,allow_nil?: false,default: "JS"endrandom_paramsdorandomMyRandom# Optional: specify your custom random generatorendend# Basic usagePost.random_params!(:create)=>%{author: "author-81491",title: "title-388112",content: nil,tag: "JS"}# With initial paramsPost.random_params!(:create,%{author: "James"})=>%{author: "James",title: "title-388112",content: nil,tag: "JS"}# With optionsPost.random_params!(:create,%{author: "James"},%{enforce_random: [:content],exclude: [:title],include_defaults?: false})=>%{author: "James",content: "content-38128"}By default, it generates random values for accepts and arguments that have allow_nil?: false and no default value (default == nil). In the example above, author and title fall into this category.
For accepts and arguments that match the name or source_attribute of a belongs_to relationship:
- In
createactions, they are generated withnilvalues - In other actions, they are not generated at all
This behavior exists because:
- In
createactions, excluding a value is equivalent to setting it tonil - In
updateactions, excluding a value preserves the existing relationship, while explicitly setting it tonilremoves the relationship
enforce_random: Forces generation of random values for specified accepts/arguments, overriding the default behaviorexclude: Prevents generation of random values for specified accepts/arguments, overriding the default behaviorinclude_defaults?: When set totrue, includes default values for accepts/arguments that have eitherallow_nil?: trueor a non-nil default value. Defaults totrue. In the example above, this would add%{content: nil, tag: "JS"}to the generated params.
You can implement a custom random generator by using the AshRandomParams.Random behaviour:
defmoduleMyRandomdouseAshRandomParams.Random@implAshRandomParams.Randomdefrandom(%{type: Ash.Type.Integer},_opts,_context)do777end@implAshRandomParams.Randomdefrandom(attr_or_arg,opts,context)do# Fallback to DefaultRandom for all other typesAshRandomParams.DefaultRandom.random(attr_or_arg,opts,context)endend- Automatically generates random values for action accepts and arguments
- Supports custom random value generators
- Useful for testing and development
Add ash_random_params to your list of dependencies in mix.exs:
defdepsdo[{:ash_random_params,"~> 0.2.1"}]endMIT