Class: RunningMan::ActiveRecordBlock

Inherits:
Block
  • Object
show all
Defined in:
lib/running_man/active_record_block.rb

Overview

Allow simple setup:

RunningMan.setup_on Test::Unit::TestCase, :ActiveRecordBlock

See README for instructions on use.

Defined Under Namespace

Modules: TestClassMethods

Instance Method Summary collapse

Methods inherited from Block

#initialize, #run_always, #run_once?

Constructor Details

This class inherits a constructor from RunningMan::Block

Instance Method Details

#clear_databaseObject



63
64
65
66
67
68
# File 'lib/running_man/active_record_block.rb', line 63

def clear_database
  conn = ActiveRecord::Base.connection
  conn.tables.each do |table|
    conn.delete "DELETE FROM #{table}"
  end
end

#run(binding) ⇒ Object

Sets up an ActiveRecord transition before every test.



32
33
34
35
# File 'lib/running_man/active_record_block.rb', line 32

def run(binding)
  super
  setup_transaction
end

#run_once(binding) ⇒ Object

Clear the database before running the block.



26
27
28
29
# File 'lib/running_man/active_record_block.rb', line 26

def run_once(binding)
  clear_database
  super
end

#set_ivar(binding, ivar, value) ⇒ Object

reload any AR instances



56
57
58
59
60
61
# File 'lib/running_man/active_record_block.rb', line 56

def set_ivar(binding, ivar, value)
  if value.class.respond_to?(:find)
    value = value.class.find(value.id)
  end
  super(binding, ivar, value)
end

#setup(test_class) ⇒ Object

Ensure the block is setup to run first, and that the test run is wrapped in a database transaction.



19
20
21
22
23
# File 'lib/running_man/active_record_block.rb', line 19

def setup(test_class)
  block = self
  test_class.setup    { block.run(self) }
  test_class.teardown { block.teardown_transaction }
end

#setup_transactionObject

Open a new transaction before running any test.



38
39
40
41
42
43
44
# File 'lib/running_man/active_record_block.rb', line 38

def setup_transaction
  ActiveRecord::Base.connection.increment_open_transactions
  if ActiveRecord::Base.connection.repond_to?(:transaction_joinable=)
    ActiveRecord::Base.connection.transaction_joinable = false
  end
  ActiveRecord::Base.connection.begin_db_transaction
end

#teardown_transactionObject

Rollback our transaction, returning our fixtures to a pristine state.



47
48
49
50
51
52
53
# File 'lib/running_man/active_record_block.rb', line 47

def teardown_transaction
  if ActiveRecord::Base.connection.open_transactions != 0
    ActiveRecord::Base.connection.rollback_db_transaction
    ActiveRecord::Base.connection.decrement_open_transactions
  end
  ActiveRecord::Base.clear_active_connections!
end