Last Updated: February 25, 2016
·
8.962K
· kugaevsky

Database cleaner, RSpec and Capybara configuration.

Configuring Database Cleaner to work with RSpec and Capybara could be a little bit tricky.

RSpec.configure do |config|
  # If you're not using ActiveRecord, or you'd prefer not to run 
  # each of your examples within a transaction, remove the following 
  # line or assign false instead of true.
  config.use_transactional_fixtures = false

  # Clean up and initialize database before 
  # running test exmaples
  config.before(:suite) do
    # Truncate database to clean up garbage from 
    # interrupted or badly written examples
    DatabaseCleaner.clean_with(:truncation)

    # Seed dataase. Use it only for essential
    # to run application data.
    load "#{Rails.root}/db/seeds.rb"
  end

  config.around(:each) do |example|
    # Use really fast transaction strategy for all 
    # examples except `js: true` capybara specs
    DatabaseCleaner.strategy = example.metadata[:js] ? :truncation : :transaction

    # Start transaction
    DatabaseCleaner.cleaning do

      # Run example
      example.run
    end

    load "#{Rails.root}/db/seeds.rb" if example.metadata[:js]

    # Clear session data
    Capybara.reset_sessions!
  end
end

4 Responses
Add your response

Since this line is assignment and not equality comparison, won't it always return :truncation?

DatabaseCleaner.strategy = example.metadata[:js] ? :truncation : :transaction
over 1 year ago ·

Nope. It will assign result of ternary operation.

[1] pry(main)> foo = nil
=> nil
[2] pry(main)> bar = foo ? :truncation : :transaction
=> :transaction
over 1 year ago ·

example.metadata[:js] will return true or nil (false) so the ternary operation will work.

over 1 year ago ·

Any idea how to silence the log output of all the seed commands?

over 1 year ago ·