The rails database will not destroy

I am running rails 3.0.3 and using rspec-rails 2.4.1 with the postgresql database. Whenever I run my RSpec tests, the data stays at the end. Does anyone know how to get rails or rspec to erase test environment data between each use?

Please tell me if there is any additional information that could facilitate the answer to my question.

Thanks!
Tristan

+4
source share
4 answers

Set the database_cleaner gem and then add it to your spec_helper.rb.

Spec::Runner.configure do |config| config.before(:suite) do DatabaseCleaner.strategy = :transaction DatabaseCleaner.clean_with(:truncation) end config.before(:each) do DatabaseCleaner.start end config.after(:each) do DatabaseCleaner.clean end end 
+10
source

Use transactional examples to roll back data after each test run

 RSpec.configure do |config| config.use_transactional_examples = true end 
+5
source

Another possibility that I just missed is using the wrong before block.

I accidentally set the before block as all instead of each :

 before :all do user = FactoryGirl.create(:user) sign_in user end 

This caused the user to stick to the entire rspec mileage in the rspec , which caused validation errors.

Instead, before should be each so that everything is clean with rspec run:

 before :each do user = FactoryGirl.create(:user) sign_in user end 

If you make this mistake, you may have to manually clear the test database before everything returns to normal. The easiest way to do this is probably to truncate each of the tables (except for schema_migrations ).

0
source

You do not need any additional stone to clear the test database between runs. In spec_helper.rb, configure rspec as follows:

 RSpec.configure do |c| c.around(:each) do |example| ActiveRecord::Base.connection.transaction do example.run raise ActiveRecord::Rollback end end end 
0
source

Source: https://habr.com/ru/post/1338018/


All Articles