Turnip and DatabaseCleaner

I've been working on some Turnip BDD scenarios for an existing site and just getting through the login process has been "interesting".

In general, I've just been working through the flow and when I come across some data that I need I either create a factory_girl object, or make a mock/double of a method. This was the case when I had to have some country data in the application. I dutifully created a factory and got everything set up. Binding.pry come to my rescue when I was still having problems. Imagine my surprise when my data wasn't there.

I sat for a few minutes to think about it, but then thought it must be DatabaseCleaner doing its thing. When I commented out some setup in my rails_helper.rb file, I found that was the case. I love using DatabaseCleaner for my specs, so ditching that wasn't an option.

At first, my DatabaseCleaner looked something like this:

config.before(:suite) do
  DatabaseCleaner.clean_with(:truncation)
end

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

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

config.before(:each) do
  DatabaseCleaner.start
end

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

but the last two blocks were cleaning the transaction after each 'step' block in Turnip – because it is RSpec. What I finally found in the rspec docs, having to do with Cucumber, but also works for Turnip is adding this code:

config.before(:each, type: :feature) do
  # :rack_test driver's Rack app under test shares database connection
  # with the specs, so continue to use transaction strategy for speed.
  driver_shares_db_connection_with_specs = Capybara.current_driver == :rack_test

  if !driver_shares_db_connection_with_specs
    # Driver is probably for an external browser with an app
    # under test that does *not* share a database connection with the
    # specs, so use truncation strategy.
    DatabaseCleaner.strategy = :truncation
  end
end

Works like a charm now.

Share this post