ruby-on-rails - 为什么 Rails 不会在运行之间重置测试数据库

标签 ruby-on-rails testing factory-bot minitest

rails 代码库中有注释表明测试数据库应该在运行之间重置

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

配置/数据库.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:

这对我来说似乎不是这种情况。

我正在使用 factory girl 生成测试模型,这里是一个示例工厂

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

播客应该有一个唯一的 feed_url,所以我验证它在模型中的唯一性。

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

test_helper.rb 中,我检查所有工厂

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

FactoryGirl.lint

我的测试创建一个播客,构建另一个同名的播客,然后断言第二个 无效。

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

我第一次运行测试时,它执行时没有错误,并且测试全部通过。 我第二次运行测试时,Factory Girl lint 失败,因为播客 feed_url 已被占用。

为什么不在运行之间重建测试数据库?

最佳答案

我们有一个更复杂的 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

你也可以使用 gem,但我没有任何经验:http://rubygems.org/gems/database_cleaner .

关于ruby-on-rails - 为什么 Rails 不会在运行之间重置测试数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24195715/

相关文章:

ruby-on-rails - 设计测试数据库记录同时测试的冲突

ruby-on-rails - rails : Multiple references to the same model error

ruby-on-rails - ActiveRecord 模型 'type' 多态关联列包括关联模型的命名空间

android - 我可以对其他应用程序使用 Appium 运行测试吗?

reactjs - enzyme Jest window.getSelection() 不起作用

python - 从管理命令运行时,Django-nose 测试用例给出断言错误

ruby-on-rails - 未定义方法 where for #<Array :0x007fd619b022b8>

ruby-on-rails - 测试 'create' Controller 操作的正确方法是什么?

ruby - 在 RSpec 上下文中包含 FactoryGirl 方法?

ruby-on-rails - 带有局部变量的 FactoryGirl