Automatic associations in ruby on rails fixtures

和自甴很熟 提交于 2019-11-30 17:16:14

Reading the API documentation, this is exactly how autogenerated fixtures are supposed to behave -- if you want to have a specific ID value for a fixture in advance, you should probably just assign it yourself.

If not, well, from the API docs:

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.
crazycrv

This is how you get an autogenerated id of the fixture label.

Fixtures.identify(:reginald)
Edo

Since I don't have enough reputation to comment, this is the actual Rails 4.1 documentation:

http://edgeapi.rubyonrails.org/classes/ActiveRecord/FixtureSet.html#class-ActiveRecord::FixtureSet-label-Fixture+label+interpolation

Under Fixture label interpolation:

monkey_id: <%= ActiveRecord::FixtureSet.identify(:reginald) %>
pirate_id: <%= ActiveRecord::FixtureSet.identify(:george) %>

The fixture's id comes directly from hashing its name (that's how "we can discover any fixture‘s ID without loading anything, as long as we know the label")

automated test to enforce fixture integrity

  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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!