执行rails test
时,rails
默认执行下面的操作:
- Remove any existing data from the table corresponding to the fixture
- Load the fixture data into the table
- Dump the fixture data into a variable in case you want to access it directly
项目背景:
当前项目中,使用fixture
准备测试数据,rails 5
中默认关联数据必须存在,假如我们有两张表customers
和customer_types
,为保证测试数据完整,我们需要准备这两张表的fixture
。customer_types
为常量表,种子数据存储在seeds.rb
中,为避免重复定义,我们可以通过配置,让执行rails test
的时候直接加载seeds.rb
,这样就不需要test/fixtures/customer_types.yml
了。
对于常量表,我们通常会将其放在db/seeds.rb
中,如果想把seeds.rb
里面的数据加载到测试数据库中,有两种方法可供使用。
方法一:执行测试代码之前先执行db/seeds.rb
每次执行测试代码之前,运行下面的命令:
rails RAILS_ENV=test db:seed
查看上述操作是否生效的方法:打开console
,执行以下命令,使用测试数据库查询对应数据是否加载成功
ActiveRecord::Base.connection.execute 'use sample_test'
方法二:test_helper
中配置加载
class ActionSupport::TestCase
setup :load_seeds
protected
def load_seeds
load "#{Rails.root}/db/seeds.rb"
end
end
此方法会在每个test
块中优先加载db/seeds.rb
,不推荐使用。