Zack Shapiro
Zack Shapiro

Reputation: 6998

Resetting the database between rspec runs

I have a test like this, which fails after the first run

it 'should have a login count of 1' do
  ... (creates a user with '[email protected]' as the email)

  expect(user.login_count).to eq 1
end

The test fails because each time I run it, that user is still in the database and the login count keeps incrementing.

The login_count keeps incrementing because of a method in my program which either finds or creates the user, each time though, it increments the login_count by 1

What's the best way to have the test think the database is clear each time it runs?

Upvotes: 1

Views: 460

Answers (1)

In order to have a clean state in the database among each test execution you may want to use the database cleaner gem: https://github.com/DatabaseCleaner/database_cleaner

Rspec example setup (Extracted from github)

RSpec.configure do |config|

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

 config.around(:each) do |example|
   DatabaseCleaner.cleaning do
   example.run
 end

end

Upvotes: 3

Related Questions