测试删除种子数据

测试删除种子数据

本文介绍了防止 Rails 测试删除种子数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用seeds.rb来填充一些状态模型参考数据:

I am using seeds.rb to populate some State model reference data:

State.create :name => 'Alabama', :abbreviation => 'AL'
State.create :name => 'Alaska', :abbreviation => 'AK'
# ...

虽然我没有使用状态装置(因为它是种子数据,我认为纯粹为了测试而复制它不会是 DRY),但 Rails 测试框架似乎在期间删除了所有状态种子数据测试.(我正在删除、重新创建、迁移和重新播种测试数据库,并在单元测试运行之前确认数据存在.)

Although I am not using state fixtures (since it's seed data to begin with, I think it wouldn't be DRY to have to duplicate this purely for tests), the Rails testing framework seems to delete all the State seed data during testing. (I am dropping, recreating, migrating and reseeding the test db, and confirmed the data is there prior to a unit test running.)

结果是这个断言在seeds.rb 中成功,但在单行测试中失败:

The result is this assertion succeeding in seeds.rb but failing in a one-line test:

assert_equal 51, State.all.size

1) Failure:
test_state_seeds_are_present(StateTest) [/test/unit/state_test.rb:24]:
<51> expected but was
<0>.
1 tests, 1 assertions, 1 failures, 0 errors

我已经尝试在基本测试类fixtures语句中明确列出非状态模型,以及翻转事务性fixtures标志(正如预期的那样,这只会影响测试期间创建的记录).当然,正在考虑的测试本身不会删除这些记录.

I have tried both explicitly listing non-State models in the base test class fixtures statement, as well as flipping the transactional fixtures flag (as expected, this only affects records created during the test). Naturally the test under consideration is not itself deleting these records.

状态记录总是被删除.有没有办法让 Rails 摆脱种子数据?我是否需要复制夹具中的所有数据以确保重新加载它?如果没有重大政治事件,我预计州数据会相对稳定.

The State records are always deleted. Is there a way to tell Rails to just get its hands off the seed data? Do I need to duplicate all the data in fixtures to make sure it gets re-loaded? Short of a major political event, I would expect the state data to be relatively stable.

tia

推荐答案

测试从数据库中删除所有数据,然后加载您的设备(如果有).

Tests delete all the data from the database and then load your fixtures (if you have any).

您需要让您的测试助手在测试运行之前加载种子文件.有几种方法可以做到这一点,请查看我的类似问题:如何将db:seed数据自动加载到测试数据库中?

You need to get your test helper to load the seed file before the tests run. There are a couple ways to do that, check out my similar question: How to load db:seed data into test database automatically?

最简单的方法可能就是添加

The easiest way is probably just to add

需要#{Rails.root}/db/seeds.rb"

到 test_helper.rb 文件的顶部(假设您使用内置测试框架).

to the top of your test_helper.rb file (assuming you use the built-in testing framework).

这篇关于防止 Rails 测试删除种子数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 13:31