When writing unit tests for model classes, it helps to print database queries on the STDOUT console. We can achieve this on a global level however I normally don’t like to muck with defaults to achieve my local convenience so I came up with the following:
def with_activerecord_log_redirected_to(stream)
old_logger = ActiveRecord::Base.logger
begin
ActiveRecord::Base.logger = Logger.new(stream)
ActiveRecord::Base.clear_active_connections!
yield
ensure
ActiveRecord::Base.logger = old_logger
ActiveRecord::Base.clear_active_connections!
end
end
With this, I can wrap my database test code as:
with_activerecord_log_redirected_to(STDOUT) do
user = User.create!(:name => ...)
...
assert something
end
However, I soon realized that calling clear_active_connections! is not without side effects. Everything is fine as long as your tests pass. If and when your test fails (which most likely will happens since order of the day is to start with a failing test
), then it leaves stale objects in database. This happens because the normal rollback cycle gets messed with when we close database connection manually.
I am guessing, nested transaction could help here. Anybody encountered this? any good solution?

[...] more here: Agile Ajax » activerecord tests: modify activerecord logging b…/b Share and [...]
[...] Agile Ajax » activerecord tests: modify activerecord logging without tripping rollback convenience… [...]