如本文所述,我在夹具中使用自动关联。例如,如果一个区域对象有一个国家/地区 id,而不是执行“country_id”:1,我执行“country”:“USA”。“USA”是我的 countries.yml 文件中的一个标签,所以fixtures 知道如何处理这个问题。但是,这仅在您没有为国家对象指定 ID 值时才有效。所以我不能将美国的 ID 指定为 1。但如果我不将它指定为 1,它最终会是一个很大的值 8974343 ......这有点奇怪。有没有办法让固定装置自动生成不是超高的 id?....或者这样可以吗?
问问题
12210 次
5 回答
24
这就是你如何获得夹具标签的自动生成的 id。
Fixtures.identify(:reginald)
于 2010-07-14T08:00:58.147 回答
22
阅读 API 文档,这正是自动生成的夹具应该如何表现的——如果您想提前为夹具指定一个特定的 ID 值,您可能应该自己分配它。
如果没有,那么从 API 文档:
The generated ID for a given label is constant, so we can discover any fixture‘s ID without loading anything, as long as we know the label.
于 2009-04-18T18:25:54.600 回答
17
由于我没有足够的声誉发表评论,这是实际的 Rails 4.1 文档:
在夹具标签插值下:
monkey_id: <%= ActiveRecord::FixtureSet.identify(:reginald) %>
pirate_id: <%= ActiveRecord::FixtureSet.identify(:george) %>
于 2014-04-09T11:47:54.623 回答
3
夹具的 id 直接来自其名称的散列(这就是“只要我们知道标签,我们就可以在不加载任何东西的情况下发现任何夹具的 ID”)
于 2009-07-12T02:21:17.250 回答
1
自动化测试以强制夹具完整性
class FixtureIntegrityTest < ActiveSupport::TestCase
context "fixture integrity" do
should "work" do
fixtures = Dir["test/fixtures/*.yml"].map do |file|
[file, File.basename(file).sub(/\..*/, "").singularize, YAML.load(ERB.new(File.read(file)).result)]
end
failures = fixtures.reject(&:last).map { |file,*| "#{file} is empty!"}
failures = failures.presence || fixtures.map do |_, klass, content|
content.select{ |_,fixture| fixture["id"] }.map do |name, _|
fixtures.map do |file, _, content|
content.select { |_,fixture| fixture[klass] == name }.map do |_, fixture|
"#{file} uses #{klass}: #{name}, but should use the id!"
end
end
end
end.flatten.compact
assert_equal [], failures
end
end
end
于 2014-08-18T20:05:59.100 回答