开发者

Rails database testing and clearing

开发者 https://www.devze.com 2023-04-06 17:09 出处:网络
Let\'s imagine this: class ModTest < ActiveSupport::TestCase test \"something\" do m1 = Mod.new # test some things

Let's imagine this:

class ModTest < ActiveSupport::TestCase
   test "something" do
     m1 = Mod.new
     # test some things
     assert m1.save
   end

   test "whatever" do
     m2 = Mod.new
     # test other things
     assert m2.save
   end
end

Before the 2n开发者_运维百科d test case gets executed, the one called whatever, will the database be cleared, or will it contain the object added by the first test case? Can this behaviour be controlled/customised?


Not 100% sure on what the default behavior is, I've been using the database_cleaner gem for this purpose. Below is the relevant code in my spec_helper.rb:

require 'database_cleaner'

RSpec.configure do |config|

  # Truncated for brevity

  config.before :suite do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with :truncation
  end

  config.before :each do
    DatabaseCleaner.start
  end

  config.after :each do
    DatabaseCleaner.clean
  end
end

One caveat, if you go this route make sure you take out the config.use_transactional_fixtures line in the default spec_helper.rb if you use the transaction cleaning strategy - leaving it set to true causes transaction within transaction errors (at least for sqlite databases).

0

精彩评论

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

关注公众号