Skip to content

abstract struct Athena::ORM::Spec::DBTestCase
inherits Athena::Spec::TestCase #

Base ASPEC::TestCase for tests that use the database. Each test runs in a transaction that's rolled back once the test is done, so tests don't see each other's data.

Implement #entity_manager_factory to return the factory the entity manager of each test is created by, such as in an abstract test case the application's specs share:

# spec/spec_helper.cr
ORM = AORM::EntityManagerFactory.new DB.open ENV["DATABASE_URL"]

abstract struct AppDBTestCase < AORM::Spec::DBTestCase
  def entity_manager_factory : AORM::EntityManagerFactory
    ORM
  end
end

# spec/user_repository_spec.cr
struct UserRepositoryTest < AppDBTestCase
  def test_find_by_name : Nil
    user = User.new
    user.name = "George"

    self.em.persist user
    self.em.flush

    self.em.repository(User).find_one_by(name: "George").should be user
  end
end

The code under test must use #em. Queries on any other connection don't see the test's data, and what they write is committed.

Tip

Applications using the ORM through AORM::Bundle can instead include AORM::Spec::DatabaseTransaction into their test cases.

Note

MySQL and MariaDB implicitly commit the transaction on statements that change the schema, such as CREATE TABLE. PostgreSQL aborts the transaction when a statement fails, so the test's later statements fail too.

Note

A test case that overrides #tear_down must call super, which rolls back the transaction.

Methods#

#em : AORM::EntityManager#

Returns the entity manager of the current test, on a connection checked out from the pool of the #entity_manager_factory, with a transaction begun.

It's created the first time it's needed, so tests that don't use it don't check out a connection.

View source

abstract #entity_manager_factory : AORM::EntityManagerFactory#

Returns the factory the entity manager of each test is created by.

View source

#tear_down : Nil#

Closes the entity manager of the current test, if one was created, rolling back its transaction and returning its connection to the pool.

View source