在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
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:
这对我来说似乎不是这种情况。
我正在使用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已经被占用。 为什么运行之间测试数据库没有被重置?