未定义的方法`use_transactional_fixtures ='在新的Rails 3项目中

时间:2011-05-05 21:10:36

标签: ruby-on-rails testing

尝试使用MongoDB和Mongoid在Rails3项目中运行测试时出错:

undefined method `use_transactional_fixtures=' for ActiveSupport::TestCase:Class

这是一个在3.0.7上运行的全新项目。我的test_helper.rb文件就是这样:

ENV["RAILS_ENV"] = "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'

class ActiveSupport::TestCase

  self.use_transactional_fixtures = true

end

这只是一个ActiveRecord方法吗?我在其他也使用ActiveSupport :: TestCase的rails项目中没有这个问题。另外,我使用Fabricator生成我的测试数据,但这并不能解释这个错误。

2 个答案:

答案 0 :(得分:3)

所以这是交易:use_transactional_filters是/rails/test_helper.rb中定义的方法

module ActiveRecord
  module TestFixtures
    extend ActiveSupport::Concern

    included do

      class_attribute :use_instantiated_fixtures   # true, false, or :no_instances
    end
  end
end

所以实际上它是ActiveRecord特有的。由于我没有在我的项目中使用ActiveRecord,这没有任何效果,我将不得不找到另一种方法来在测试运行之间清除我的数据库。

答案 1 :(得分:1)

这是一个可以用来在每次测试后删除所有表的一行黑客:

Mongoid.master.collections.select {|c| c.name !~ /system/ }.each(&:drop) # transactional fixtures hack for mongo

或者正如JP指出的那样,数据库清理器gem似乎对此有用: https://github.com/bmabey/database_cleaner

在我的测试中,database_cleaner gem的速度提高了约4%,我猜是因为它使用截断而不是删除表。以下是使用数据库清理程序和rspec

的示例spec_helper.rb文件
  ENV["RAILS_ENV"] ||= 'test'
  require File.expand_path("../../config/environment", __FILE__)
  require 'rspec/rails'
  require 'capybara/rspec'

  require 'database_cleaner'
  DatabaseCleaner.strategy = :truncation

  # Requires supporting ruby files with custom matchers and macros, etc,
  # in spec/support/ and its subdirectories.
  Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

  RSpec.configure do |config|
    config.mock_with :mocha

    config.before(:each) do
      DatabaseCleaner.clean
      #Mongoid.master.collections.select {|c| c.name !~ /system/ }.each(&:drop) # transactional fixtures hack for mongo
    end
  end