在测试过程中,使用find_or_create_by
将域数据放入模型中对我造成了一些问题。我相信问题是数据被插入并且在测试的db事务中定义了所有的常量。在测试示例之后,db事务回滚,留下仍然实例化的常量指向不再存在的记录。
所以我把域数据放入seeds.rb
。为了防止这种情况Docunext笔记,模型实例化的问题,之前的数据是在数据库中,我使用原始SQL的插入,因为这样的:
# in db/seeds.rb
ActiveRecord::Base.connection.execute "INSERT INTO invoice_statuses(name) values ('Approved'), ('Sent'), ('Paid');"
我配置database_cleaner宝石跳过所有域表在测试之间清理出当数据库:
# in spec/support/database_cleaner.rb
RSpec.configure do |config|
domain_data = %w[aql_results invoice_statuses service_results remark_types]
config.before(:suite) do
DatabaseCleaner.strategy = :deletion, { except: domain_data }
DatabaseCleaner.clean
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each, :js => true) do
DatabaseCleaner.strategy = :deletion, { except: domain_data }
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
这里的我们指的是这个概念:http://enterpriserails.chak.org/full-text/chapter-7-domain-data – Docunext