<commit_before>= Cranky

Cranky is a fixtures replacement inspired by the excellent Factory Girl, but simpler and with less magic going on.

In short use this if you want to naturally create factory methods that you feel 100% in control of and without a block in sight.

== Install

First install the gem...

  gem install cranky

Or for rails stick it in your environment.rb or Gemfile as normal...

  # environment.rb
  config.gem "cranky"

  # Gemfile
  gem "cranky"

Then in your spec_helper.rb ...

  # spec_helper.rb
  require "cranky"
  require "factories/my_factories"

The above assumes that you have created your factory methods in a file called my_factories.rb in the spec/factories directory.
You can create as many different factory files as you want, just require them in the same way.

== In a Nutshell

Cranky steals its core syntax from Factory Girl...

  Factory.build(:user)                  # Build a user instance without saving
  Factory.create(:user)                 # Build and save a user instance
  Factory.build(:user, :name => "Ian")  # Override a default attribute value
  Factory.attributes_for(:user)         # Return a set of valid attributes rather than the object

Cranky allows you to build factories via std Ruby methods, like this...

  # factories/my_factories.rb
  class Cranky          # Your factory must use the Cranky class

    # Simple factory method to create a user instance, you would call this via Factory.build(:user)
    def user
      # Define attributes via a hash, generate the values any way you want
      define :name    => "Jimmy",               
             :email   => "<EMAIL>",   # An 'n' counter method is available to help make things unique
             :role    => :user,
             :address => default_address         # Call your own helper methods to wire up your associations
    end

    # Easily create variations via the inherit helper, callable via Factory.build(:admin)
    def admin
      inherit(:user, :role => :admin)
    end

    # Return a default address if it already exists, or call the address factory to make one
    def default_address
      @default_address ||= create(:address) 
    end

    # Alternatively loose the DSL altogether and define the factory yourself, still callable via Factory.build(:address)
    def address
      a = Address.new
      a.street = "192 Broadway"
      a.city = options[:city] || "New York"   # You can get any caller overrides via the options hash
      a                                       # Only rule is the method must return the generated object 
    end

  end

= Details

== Define Your Factories

This is where Cranky really shines, if you can create Ruby methods you can pretty much create your factories without having to refer to the syntax documentation ever again.

The only rules are:

1. Your factory must use the +Cranky+ class
2. Your factory method must return the object you wanted to create
3. You can access the overrides passed in via options[:key]  (not really a rule!) 

So for example to create a simple user factory...

  # factories/my_factories.rb
  class Cranky

    # Simple factory method to create a user instance, you would call this via Factory.build(:user)
    def user
      u       = User.new
      u.name  = options[:name] || "Jimmy"                 # Use the passed in name if present, or the default
      u.email = options[:email] || "<EMAIL>"   # Give each user a unique email address
      u.role  = options[:role] || :user
      u
    end

  end

Now of course you are working in straight Ruby here, so you can extend this any way you want as long as you follow the above rules. 

For example here it is with the capability to automatically create a default address association...

  # factories/my_factories.rb
  class Cranky

    # Return the default address if it already exists, or call the address factory to make one
    def default_address
      @default_address ||= create(:address) 
    end

    def user
      u         = User.new
      u.name    = options[:name] || "Jimmy"
      u.email   = options[:email] || "<EMAIL>"
      u.role    = options[:role] || :user
      u.address = default_address
      u
    end

    ... # Create the address factory in the same way

  end

Quite often the database will be cleared between tests but the instance variable in the factory will not necessarily be reset which could lead to problems if the tests check for the associated record in the database.
So a nice tip is to implement default associations like this (assuming you're using Rails)...

  # Return the default address if it already exists, or call the address factory to make one
  def default_address
    # If the default address exists, but has been cleared from the database...
    @default_address = nil if @default_address && !Account.exists?(@default_address.id)
    @default_address ||= create(:address) 
  end

You can pass additional arguments to your factories via the overrides hash...

  Factory.build(:user, :new_address => true)

  def user
    u         = User.new
    u.name    = options[:name] || "Jimmy"
    u.email   = options[:email] || "<EMAIL>"
    u.role    = options[:role] || :user
    u.address = options[:new_address] ? create(:address) : default_address
    u
  end

== Helpers

Of course its nice to get some help...

=== Define

Most of your factories are likely to simply define a list of mimimum attribute values, use the define helper for this. 

  # The user factory re-written using the define helper
  def user
    define :name    => "Jimmy",
           :email   => "<EMAIL>",
           :role    => :user,
           :address => default_address
  end

Note that you don't have to worry about handling the overrides here, they will be applied automatically if present, just define the defaults.

The best thing about this is that there are no pesky blocks to worry about. The define argument is just a regular hash, you have complete freedom to choose how to generate the values to be passed into it.

The define method will return the object, you can grab this for additional manipulation as you would expect...

  def user
    u = define :name    => "Jimmy",
               :email   => "<EMAIL>",
               :role    => :user,
               :address => default_address
    u.do_something
    u               # Remember to return it at the end
  end

If for any reason you want to have your factory method named differently from the model it instantiates you can pass in a :class attribute to the define method...

  # Called via Factory.create(:jimmy)
  def jimmy
    u = define :class   => :user, 
               :name    => "Jimmy",
               :email   => "<EMAIL>",
               :role    => :user,
               :address => default_address
  end

=== Inherit

You can inherit from other factories via the inherit method. So for example to create an admin user you might do...

  # Called via Factory.create(:admin)
  def admin
    inherit(:user, :role => :admin)  # Pass in any attribute overrides you want
  end

=== Unique Attributes (n)

If you want to generate unique attributes you can call the n method which will automatically increment the next time it is called.

Note that every time n is called it will increment, it does not implement a unique counter per attribute.

=== Reset

Clear all instance variables in the factory. This may be useful to run between tests depending on your factory logic...

  before(:each) do
    Factory.reset
  end

=== Debug

Sometimes it is useful to be warned that your factory is generating invalid instances (although quite often your tests may intentionally generate invalid instances, so use this with care). By turning on debug the Factory will raise an error if the generated instance is invalid...

  Factory.debug = true

Note that this relies on the instance having a valid? method, so in practice this may only work with Rails.
<commit_msg>Minor update to README<commit_after>= Cranky

Cranky is a fixtures replacement inspired by the excellent Factory Girl, but simpler and with less magic going on.

In short use this if you want to naturally create factory methods that you feel 100% in control of and without a block in sight.

== Install

First install the gem...

  gem install cranky

Or for rails stick it in your environment.rb or Gemfile as normal...

  # environment.rb
  config.gem "cranky"

  # Gemfile
  gem "cranky"

Then in your spec_helper.rb ...

  # spec_helper.rb
  require "cranky"
  require "factories/my_factories"

The above assumes that you have created your factory methods in a file called my_factories.rb in the spec/factories directory.
You can create as many different factory files as you want, just require them in the same way.

== In a Nutshell

Cranky steals its core syntax from Factory Girl...

  Factory.build(:user)                  # Build a user instance without saving
  Factory.create(:user)                 # Build and save a user instance
  Factory.build(:user, :name => "Ian")  # Override a default attribute value
  Factory.attributes_for(:user)         # Return a set of valid attributes rather than the object

Cranky allows you to build factories via std Ruby methods, like this...

  # factories/my_factories.rb
  class Cranky          # Your factory must use the Cranky class

    # Simple factory method to create a user instance, you would call this via Factory.build(:user)
    def user
      # Define attributes via a hash, generate the values any way you want
      define :name    => "Jimmy",               
             :email   => "<EMAIL>",   # An 'n' counter method is available to help make things unique
             :role    => "pleb",
             :address => default_address         # Call your own helper methods to wire up your associations
    end

    # Easily create variations via the inherit helper, callable via Factory.build(:admin)
    def admin
      inherit(:user, :role => "admin")
    end

    # Return a default address if it already exists, or call the address factory to make one
    def default_address
      @default_address ||= create(:address) 
    end

    # Alternatively loose the DSL altogether and define the factory yourself, still callable via Factory.build(:address)
    def address
      a = Address.new
      a.street = "192 Broadway"
      a.city = options[:city] || "New York"   # You can get any caller overrides via the options hash
      a                                       # Only rule is the method must return the generated object 
    end

  end

= Details

== Define Your Factories

This is where Cranky really shines, if you can create Ruby methods you can pretty much create your factories without having to refer to the syntax documentation ever again.

The only rules are:

1. Your factory must use the +Cranky+ class
2. Your factory method must return the object you wanted to create
3. You can access the overrides passed in via options[:key]  (not really a rule!) 

So for example to create a simple user factory...

  # factories/my_factories.rb
  class Cranky

    # Simple factory method to create a user instance, you would call this via Factory.build(:user)
    def user
      u       = User.new
      u.name  = options[:name] || "Jimmy"                 # Use the passed in name if present, or the default
      u.email = options[:email] || "<EMAIL>"   # Give each user a unique email address
      u.role  = options[:role] || "pleb"
      u
    end

  end

Now of course you are working in straight Ruby here, so you can extend this any way you want as long as you follow the above rules. 

For example here it is with the capability to automatically create a default address association...

  # factories/my_factories.rb
  class Cranky

    # Return the default address if it already exists, or call the address factory to make one
    def default_address
      @default_address ||= create(:address) 
    end

    def user
      u         = User.new
      u.name    = options[:name] || "Jimmy"
      u.email   = options[:email] || "<EMAIL>"
      u.role    = options[:role] || "pleb"
      u.address = default_address
      u
    end

    ... # Create the address factory in the same way

  end

Quite often the database will be cleared between tests but the instance variable in the factory will not necessarily be reset which could lead to problems if the tests check for the associated record in the database.
So a nice tip is to implement default associations like this (assuming you're using Rails)...

  # Return the default address if it already exists, or call the address factory to make one
  def default_address
    # If the default address exists, but has been cleared from the database...
    @default_address = nil if @default_address && !Account.exists?(@default_address.id)
    @default_address ||= create(:address) 
  end

You can pass additional arguments to your factories via the overrides hash...

  Factory.build(:user, :new_address => true)

  def user
    u         = User.new
    u.name    = options[:name] || "Jimmy"
    u.email   = options[:email] || "<EMAIL>"
    u.role    = options[:role] || "pleb"
    u.address = options[:new_address] ? create(:address) : default_address
    u
  end

== Helpers

Of course its nice to get some help...

=== Define

Most of your factories are likely to simply define a list of mimimum attribute values, use the define helper for this. 

  # The user factory re-written using the define helper
  def user
    define :name    => "Jimmy",
           :email   => "<EMAIL>",
           :role    => "pleb",
           :address => default_address
  end

Note that you don't have to worry about handling the overrides here, they will be applied automatically if present, just define the defaults.

The best thing about this is that there are no pesky blocks to worry about. The define argument is just a regular hash, you have complete freedom to choose how to generate the values to be passed into it.

The define method will return the object, you can grab this for additional manipulation as you would expect...

  def user
    u = define :name    => "Jimmy",
               :email   => "<EMAIL>",
               :role    => "pleb",
               :address => default_address
    u.do_something
    u               # Remember to return it at the end
  end

If for any reason you want to have your factory method named differently from the model it instantiates you can pass in a :class attribute to the define method...

  # Called via Factory.create(:jimmy)
  def jimmy
    u = define :class   => :user, 
               :name    => "Jimmy",
               :email   => "<EMAIL>",
               :role    => "pleb",
               :address => default_address
  end

=== Inherit

You can inherit from other factories via the inherit method. So for example to create an admin user you might do...

  # Called via Factory.create(:admin)
  def admin
    inherit(:user, :role => "admin")  # Pass in any attribute overrides you want
  end

=== Unique Attributes (n)

If you want to generate unique attributes you can call the n method which will automatically increment the next time it is called.

Note that every time n is called it will increment, it does not implement a unique counter per attribute.

=== Reset

Clear all instance variables in the factory. This may be useful to run between tests depending on your factory logic...

  before(:each) do
    Factory.reset
  end

=== Debug

Sometimes it is useful to be warned that your factory is generating invalid instances (although quite often your tests may intentionally generate invalid instances, so use this with care). By turning on debug the Factory will raise an error if the generated instance is invalid...

  Factory.debug = true

Note that this relies on the instance having a valid? method, so in practice this may only work with Rails.

{'fraction_non_alphanumeric': 0.06621723790322581, 'fraction_numerical': 0.0011340725806451614, 'mean_word_length': 2.782888465204957, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 59, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3650698', 'n_tokens_mistral': 4148, 'n_tokens_neox': 3983, 'n_words': 2103}