Let’s say I have this:
test “assign the same transaction id to all memos created in the block”
do
school = site = nil
Memo.group do
school = make :school
site = make :site
end
assert_not_nil school.memos.last.transaction_id
assert_not_nil site.memos.last.transaction_id
assert_equal school.memos.last.transaction_id,
site.audit_memos.last.transaction_id
end
#helper
def make(factory_name, *args, &block)
factory_name = factory_name.model_name.singular if Class ===
factory_name
options = args.extract_options!
count = args.first || 1
records = []
count.times do
record = case factory_name
when :user then Factory.custom(factory_name, options, &block)
else Factory(factory_name, options, &block)
end
records << record
end
records.many?? records : records.first
end
#memo
def self.group(&block)
self.current_transaction_id = maximum(:transaction_id) ?
maximum(:transaction_id) + 1 : 100000
transaction { yield }
ensure
self.current_transaction_id = nil
end
So basically when the test is run, make() in the block gets executed,
passing a key that is associated with a Factory (factory girl). So at
some point factory_name holds Site. And we run the times iterator 1 time
and invoke Factory() which defines a series of attributes for a Site
object, for example:
Factory.define :site do |f|
f.sequence(:number) { |n| “TEST-#{n}” }
f.state { SiteState[:initialized] }
f.target 50
f.est Date.current
end
So now we have object and some attributes stored in a block that gets
passed to group class method. The &block indicates that the block is
passed by reference. We use the yield keyword to yield the contents of
the block in a hash of the transaction() method. But exactly does it do?
The ruby documentation just says it protects sql statements by rolling
back if transaction fails:
But that’s not helpful in this case, as to what transaction() is doing
above.
Thanks for response.
I no longer receive emails from the board when questions are asked and
answered. I hope I am still on the board.