Search code examples
sql-server-2008rspec-railsdatabase-cleaner

Using the rails gem database_cleaner when rSpec testing and using activerecord-sqlserver-adapter


I am using the activerecord-sqlserver-adapter gem to connect to a 2008 SQL Server Database within my rails application. Please note that I do connect to multiple db's throughout my application using 'establish_connection'. I use rSpec to test my application and I want to remove the entries from the DB that rSpec creates. I googled around and found that the database_cleaner gem would be the answer to my problem so I included the Gem and setup my railsappname/spec/spec_helper.rb as so:

require 'database_cleaner'

RSpec.configure do |config|

  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end

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

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

I also updated the following line to be false

config.use_transactional_fixtures = false

To my rails_helper.rb RSpec.configure block as that is where that line was originally.

I have also tried changing my strategy to :truncation and that has not made a difference. The data is still being inserted in to the DB and not being deleted after the test has completed. Is this a limitation to the activerecord-sqlserver-adapter and are there workarounds for this? Is this issue being caused by the fact I connect to multiple db's within my app? I have googled around for a while and have not seen anyone else experiencing this same issue so any advise is much appreciated!


Solution

  • Thanks for the heads up, but your stack overflow question is really not about SQL Server or the adapter. It is really a by product of how your software is put together. I'm gonna bet it all has something to do with how you establish connections too. Check out this comment on the adapter.

    https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/issues/173#issuecomment-4427121

    Basically you want to make sure you only have one model that champions a connection so you can manage it. Most gems only know about ActiveRecord::Base. So if you have an app that has many databases, please make sure you do all the things that entails. It is tricky. So much so I even wrote a blog article about it. You should read it :)

    http://technology.customink.com/blog/2015/06/22/rails-multi-database-best-practices-roundup/

    Lastly... this is purely subjective... but I am a big fan of Rails transactional fixtures and not running your test with an empty database. My advice:

    Again, purely subjective, but I hope that last bit helps. Cheers.