Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rspec clean database before running

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=

like image 416
Hugo Avatar asked Dec 14 '22 20:12

Hugo


1 Answers

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.

like image 138
ian Avatar answered Dec 30 '22 07:12

ian