rspec clean database before running

狂风中的少年 提交于 2019-12-06 12:23:07

问题


I'm using RSpec in a Sinatra project. I'm testing a model which runs an after_find hook to initialize some values. I need to wipe the database before every run, and after some searching around, my spec helper file looks like this:

require "pry"
require "factory_girl_rails"
require "rspec-rails"

FactoryGirl.find_definitions

ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)

RSpec.configure do |config|
  config.use_transactional_fixtures = true
end

I'm getting the following error:

undefined method `use_transactional_fixtures=' for #<RSpec::Core::Configuration:0x007fc1c89397e8> (NoMethodError)`

I looked up the documentation for RSpec::Core::Configuration and the only mention of use_transactional_fixtures= is where it specifically states that it's rails specific. I have the 'rspec-rails' gem installed, so I don't know why it's not using it. I'm even requiring it in the spec helper file.

My initial thought was to just create a Rakefile that runs db:drop, db:create, and db:migrate and then the tests, but I'm hoping there's a slightly easier way like use_transactional_fixtures=


回答1:


I use Database Cleaner to do this. Here's something I have in a spec_helper.rb (an old one!)

RSpec.configure do |config|
  # Clean up the database
  require 'database_cleaner'
  config.before(:suite) do
    DatabaseCleaner.orm = "sequel"
    DatabaseCleaner.clean_with :truncation, {:only => %w{LIST OF TABLES HERE} } 
  end

  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end

  config.before(:each, :js => true) do
    DatabaseCleaner.strategy = :truncation
  end

  config.before(:each, :database) do
    # open transaction
    DatabaseCleaner.start
  end

  config.after(:each, :database) do
    DatabaseCleaner.clean
  end
end

I also tend to keep a separate test database from development, just for speed and to make my life easier.



来源:https://stackoverflow.com/questions/25497134/rspec-clean-database-before-running

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