undefined method `use_transactional_fixtures=' in new Rails 3 project

女生的网名这么多〃 提交于 2019-12-22 06:49:06

问题


I am getting an error when trying to run my tests in a Rails3 project, using MongoDB and Mongoid:

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

This is a brand new project running on 3.0.7. My test_helper.rb file is exactly this:

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

class ActiveSupport::TestCase

  self.use_transactional_fixtures = true

end

Is this an ActiveRecord only method? I do not have this problem in other rails projects which also use ActiveSupport::TestCase. Also, I am using Fabricator to generate my test data, but that wouldn't really explain this error.


回答1:


So here's the deal: use_transactional_filters is a method defined in /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

So in fact it is ActiveRecord specific. Since I'm not using ActiveRecord in my project, this has no effect, and I'll have to find another way to clear out my database between test runs.




回答2:


Here is a one line hack you can use to drop all tables after each test:

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

Or as JP pointed out the Database cleaner gem seems to work well for this: https://github.com/bmabey/database_cleaner

In my tests the database_cleaner gem was about 4% faster, I'm guessing because it uses truncation instead of dropping the tables. Here is a sample spec_helper.rb file that uses database cleaner and rspec

  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


来源:https://stackoverflow.com/questions/5904129/undefined-method-use-transactional-fixtures-in-new-rails-3-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!