开发者

How do I execute a SQL statement after fixtures are loaded but before the savepoint is created?

We have a model which gets a sequence number from the ID of another model, using auto_increment on the other model's table. That value gets set to zero whenever the db server is restarted, so the sequence numbers reset. To work around this, in an after_initialize block, we set the auto_increment value to the maximum sequence value plus one, and all is well.

However, in the tests, the block runs before fixtures are loaded, so the maximum comes back as nil. Then when the tests run, the value is too low and so the tests fail.

One possible solution is to update the value in a setup block, but altering the table commits the current transaction and so the rollback at the end of the test fails.

How do I alter the AUTO_INCREMENT value after fixtures are loaded, but before the savep开发者_运维问答oint is created?


Finally found a way to do this by monkey patching load_fixtures at the end of test_helper.rb:

module ActiveRecord
  module TestFixtures
    def load_fixtures_with_auto_increment_reset
      load_fixtures_without_auto_increment_reset
      # code to reset auto_increment goes here
    end

    alias_method :load_fixtures_without_auto_increment_reset, :load_fixtures
    alias_method :load_fixtures, :load_fixtures_with_auto_increment_reset
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜