Quicker ways to setup mock objects

Setting up mock objects can be somewhat tedious, so you can add the methods DomainObject.default_mock and DomainObject.custom_mock by requiring lafcadio/test.rb.

DomainObject.default_mock will commit its best guess of a typical instance of the class if one doesn't already exist, and then return that instance. Field values will be valid, but for the most part meaningless. This instance will always have a pk_id of 1, and any relations to other domain classes will refer to the default_mock of that class. Note that multiple calls to DomainObject.default_mock will return the same instance.

require 'lafcadio/test'
mock_object_store = MockObjectStore.new
ObjectStore.set_object_store mock_object_store
john = User.default_mock
puts john.first_name        # "test text"
puts john.email             # "test text"
john2 = User.default_mock
puts ( john == john2 )      # true
msg = Message.default_mock
puts ( msg.author == john ) # true

If you want to create custom mocks that are mostly the same but vary in a few fields, you can use DomainObject.custom_mock. This always commits a new instance, with specific fields set to new values.

jane = User.custom_mock( 'first_name' => 'Jane' )
puts ( john == jane )       # false

The field values that Lafcadio guesses are really pretty stupid, and are just there to be a half-step better than nil. You might want to create better values for those mock object fields, and you can do so with DomainObject.mock_values. These will affect the default values used both in DomainObject.default_mock and DomainObject.custom_mock. Note that given the open nature of Ruby classes, you can have this mock_values code in an entirely separate file, to only be required for testing.

class User < Lafcadio::DomainObject
  mock_values 'first_name' => 'John', 'last_name' => 'Doe',
              'email' => 'john.doe@email.com', 'password' => 'password',
              'birthday' => ( Date.today - 365 * 30 )
end
john = User.default_mock
puts john.first_name        # "John"
puts john.last_name         # "Doe"
puts john.email             # "john.doe@email.com"
jane = User.custom_mock(
  'first_name' => 'Jane', 'email' => 'jane.doe@email.com'
)
puts jane.first_name        # "Jane"
puts jane.last_name         # "Doe"
puts jane.email             # "jane.doe@email.com"

And if your test case includes Lafcadio::DomainMock, you can use the class method setup_mock_dobjs to auto-create default mocks as part of the setup method. These will be set as local variables. Note that if you write your own setup method in such a test case, you should remember to call super to ensure that the mock setup is run correctly.

class TestUser < Test::Unit::TestCase
  include Lafcadio::DomainMock
  setup_mock_dobjs User

  def test_first_name
    assert_equal( "John", @user.first_name )
  end
end