Test friendly

Test friendly gem provides functionality to turn off validations in test environment.

In order to turn off validations in test environment, class inherited from ActiveRecord::Base should have acts_as_test_friendly static method and test_friendly_validations block where validations should be inserted. Here is an example:

class User < ActiveRecord::Base
  acts_as_test_friendly

  attr_accessor :first_name, :last_name

  test_friendly_validations do
    validates_presence_of :first_name, :last_name
  end

end

In order to turn validations on, User.force_validations method has to be used (usually in before validation hook). Also user can optionally turn on only specific validations:

class User < ActiveRecord::Base
  acts_as_test_friendly

  attr_accessor :first_name, :last_name, :new_attribute

  test_friendly_validations do
    validates_presence_of :first_name, :last_name
  end

  test_friendly_validations(:additional) do
    validates_presence_of :new_attribute
  end

end

Here in order to turn on only additional validations, User.force_validations(:additional) construction has to be used. If tag is not specified - validation goes under :defaults tag. So, in order to turn on first and last name validation in example above, User.force_validations(:defaults) has to be used. For forcing all validations for all tags, User.force_validations(:all) should be used.

There is also drop validations functionality. It has same signature as force_validations, but different method is used. User.drop_validations

Test friendly gem is also supplied with functionality that lets turn on/off callbacks in test environment. Here is an example of class:

class User < ActiveRecord::Base
  include AllMissingUserMethods

  acts_as_test_friendly

  attr_accessor :first_name, :last_name, :new_attribute

  test_friendly_callbacks do
    after_save :send_notification_email
  end

  test_friendly_callbacks(:additional) do
    before_save :create_order_instance
  end

end

Callbacks work same way as validations, but have different methods signature (valdiations are substituted with callbacks). User.force_callbacks, User.force_callbacks(:additional), User.force_callbacks(:all), User.drop_callbacks, User.drop_callbacks(:additional), User.drop_callbacks(:all) all can be used.

At the moment gem automatically turns off validations and callbacks in every Rspec test. If you are using different testing tool, there are some methods that can help you:

1. TestFriendly::Global.drop_validations(:all) - drops all validations
2. TestFriendly::Global.force_validations(:all) - forces all validations
3. TestFriendly::Global.drop_callbacks(:all) - drops all callbacks
4. TestFriendly::Global.force_callbacks(:all) - forces all callbacks

Also you can use specific tag as parameter as well as leave parameter blank (in this case :defaults tag will be used).

Contributing to test_friendly

Copyright © 2012 Andriy Romanov. See LICENSE.txt for further details.