Why the rails do not reset the test database between runs

There are comments in the rails database indicating that the test database should be reset between runs

rake -T

rake test:all                           # Run tests quickly by merging all types and not resetting db
rake test:all:db                        # Run tests quickly, but also reset db

config / database.yml

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:

This is not like me.

I am using a factory girl to generate test models, here is a factory example

FactoryGirl.define do
  factory :podcast do
    sequence(:title)     { |n| "Podcast #{n}" }
    sequence(:feed_url)  { |n| "http://podcast.com/#{n}" }
  end
end

A podcast must have a unique feed_url, so I check its uniqueness in the model.

class Podcast < ActiveRecord::Base
  validates :feed_url, uniqueness: true, presence: true
end

Q test_helper.rbI will tie all the plants

ENV["RAILS_ENV"] ||= "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require 'minitest/autorun'

FactoryGirl.lint

My test creates a podcast, builds another with the same name, and then claims that the second is invalid.

require 'test_helper'

describe Podcast do
  describe '#feed_url' do
    it 'must be unique' do
      podcast = create(:podcast)
      new_podcast = build(:podcast, feed_url: podcast.name)

      assert_invalid podcast, :feed_url, 'has already been taken'
    end
  end
end

The first time you run the tests, it runs without errors and all tests pass. The second time I run the tests, Girl lint fails because the podcast feed_url is already done.

Why doesn't the test database rebuild between runs?

+4
3

FactoryGirl, , , , , test_helper.rb, , :

# Destroy all models because they do not get destroyed automatically
(ActiveRecord::Base.connection.tables - %w{schema_migrations}).each do |table_name|
  ActiveRecord::Base.connection.execute "TRUNCATE TABLE #{table_name};"
end

rake db:test:prepare .

, , : http://rubygems.org/gems/database_cleaner.

+6

, , , , . ActiveSupport::TestCase . ActiveRecord . reset . ActiveSupport::TestCase, Minitest::Spec, .

- minitest-rails Gemfile test_helper.rb minitest/autorun minitest/rails. DSL Minitest, .

+8

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


All Articles