防止Rails测试删除种子数据 [英] Prevent Rails test from deleting seed data

查看:87
本文介绍了防止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'
# ...

尽管我没有使用状态固定装置(因为开始时是种子数据,所以我认为不必纯粹为了测试而复制它),但是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.)

结果是此断言在seed.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语句中显式列出非状态模型,以及翻转事务性fixture标志(正如预期的那样,这只会影响测试期间创建的记录).自然,正在考虑的测试本身并不是删除这些记录.

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

require "#{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测试删除种子数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆