Run a specific rake test before running a specific test in RAILS
I am testing an app with the built-in unit testing feature provided by rails. The problem is that one test heavily depends on calculations with ids and we must test that. As active record doesn't reset auto_increment when rolling back a transaction we are having some troubles here.
Things could be fixed if there is a way to reset all database tables and load the fixtures again as if I have run just that test.
Firstly I try to define a setup method to reset all the necessary auto_increment values in this way:
def setup
ActiveRecord::Base.connection.execute("ALTER TABLE 'table_name1' AUTO_INCREMENT = 1;")
ActiveRecord::Base.connection.execute("ALTER TABLE 'table_name2' AUTO_INCREMENT = 1;")
end
开发者_如何学C
but the test failed throwing this ugly error:
ActiveRecord::StatementInvalid: Mysql::Error: SAVEPOINT active_record_1 does not exist: ROLLBACK TO SAVEPOINT active_record_1
Then I try to invoke db:test:prepare and db:fixtures:load in the setup method but this failed too. Besides, it will slow up the test a lot since the setup method is run before each test in the file, isn't it?
So how can I run those rake task just before a specific test suite or test file (don't know how to call it) and only for that one?
Thanks! :)
You should be able to delete your test database, and then run rake db:create RAILS_ENV=test
to recreate the database from within the test. If you do that in the middle of a test, however, you'll also need to re-seed the database with valid data, which can be a major pain in the ass, if that's the route you want to take.
You should also be able to use the "drop_table :table_name" stuff from migrations to do this.
HOWEVER, your tests shouldn't be written in such a way, nor should your DB be structured in such a way, they they rely on specific DB id's. Nor should your tests need to recreate whole tables just to reset the AUTO_INCREMENT value. This is almost certainly a sign that you're not using your test suite tools the way they are designed to be used. But, I also recognize that it's not a perfect world, and I'm hoping this is some kind of unusual edge case. :S
You can use a database_cleaner gem. then on your database_cleaner.rb, you can specify :pre_count
and :reset_ids
to reset you ids. I recommend to use a separate database for your test environment as well.
精彩评论