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/