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::Te开发者_JS百科stCase. Also, I am using Fabricator to generate my test data, but that wouldn't really explain this error.
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.
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
精彩评论