Search code examples
ruby-on-railsrubycapybararspec-rails

Database cleaner strategy in Rspec


Is it possible to check what the database cleaner strategy is at any point in the test cases?

How will I come to know which type of strategy is used in the test cases?

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

config.before(:example, type: :feature, js: true) do
  DatabaseCleaner.strategy = :truncation
end

require 'rails_helper'
RSpec.feature 'Login Feature', type: :feature do
  it 'invalid user login fail' do
    a = create(:normal_user, role: AdminType::OWNER)
    visit('/')
  end
end

Here, I have mentioned type as a feature in the top most describe block (Example Group), not in the example. But I have configured my database cleaner to use truncation strategy on feature type example for others using transaction strategy.

Which type of strategy will the database cleaner use, truncation or transaction?

If it uses truncation strategy, then I think that all examples under type: feature will be considered type: feature examples. Am I right?

How will I check what the current strategy is (for example, by seeing the test log)?


Solution

  • Yes - any test inside the RSpec.feature block will have tpye: :feature metadata unless it overrides by specifying another type. System specs and feature specs are basically the same thing, just Rails added an extra layer of abstraction on system tests (driven_by, etc)

    In Rails 5.1+ for feature or system tests, even if using RSpecs system tests rather than the Rails minitest based system tests, DatabaseCleaner is generally not needed. This is because Rails 5.1 added automatic sharing of the database connection between all threads in the test process while in the test environment. If you were needing a separate process to access the database during tests then you would still need DatabaseCleaner, but that's not common especially with beginning projects.