Search code examples
ruby-on-railscapybaradatabase-cleaner

database cleanup with capybara


I'm using capybara, minitest, database_cleaner gem, I'm curious database cleaner not cleanup my database after I running test, the test running well, user created and can login successfully, then I re-run test with same data, and it said the email is already taken, meaning: database_cleaner not running

below is my test

require "test_helper"
require "database_cleaner"

feature 'register new user' do
  scenario 'register', js: true do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.start
    visit '/sign_up'
    within '#new_user' do
      fill_in 'User name', with: 'user4'
      fill_in 'Email',     with: '[email protected]'
      fill_in 'Password',  with: 'password4'
      fill_in 'Password Konfirmasi', with: 'password4'
      click_button 'Sign up'
    end
    DatabaseCleaner.clean
    page.must_have_content 'USER SETTING & INFO'
  end  
end

and below is my Gemfile for testing

group :development, :test do
  gem 'selenium-webdriver', '2.53.4'
  gem 'minitest-rails-capybara'
  gem 'minitest-reporters'
  gem 'database_cleaner'
end

Solution

  • You need to put the page.must_have_content 'USER SETTING & INFO' before the DatabaseCleaner.clean line. This is because when you click a button it can return immediately while the request triggered by the button click happens asynchronously. In your case this means you click the button, then clean the database, meanwhile the request to create the new user is sent and most likely arrives after the database has already been cleared thereby creating a user that doesn't get cleared.

    Usually the DatabaseCleaner methods would be called from setup/teardown with minitest (before/append_after blocks with RSpec) to ensure that database cleaning doesn't occur until the test is complete, and that they get run even if something in the test fails.