简体   繁体   English

如何获取Rails夹具实例的内容的哈希值?

[英]How can I get a hash of the contents of a Rails fixture instance?

This is using Rails 4.2.0, Ruby 2.2.0. 这使用的是Rails 4.2.0,Ruby 2.2.0。

What I'd like to do is use the data contained in a fixture object to verify that duplicates are caught before insertion into the same database: 我想做的是使用包含在fixture对象中的数据来验证是否在插入相同数据库之前捕获到重复项:

  test "identical entries should be impossible to create" do
    dup_entry = Entry.new(entries(:test_entry))
    assert_not dup_entry.save
  end

(where Entry is a well-defined model with a controller method .new , and test_entry is a fixture containing some valid Entry instance.) (其中Entry是一个定义明确的模型,具有控制器方法.new ,而test_entry是一个包含一些有效Entry实例的装置。)

Unfortunately, this doesn't work because entries(:test_entry) is going to be an Entry , not a hash accepted by Entry.new . 不幸的是,这不起作用,因为entries(:test_entry)将是一个Entry ,而不是Entry.new接受的Entry.new

I know that I can access fixture properties with an expression of the form fixture_objname.property in the associated tests, since whatever is specified in the YAML will automatically be inserted into the database and loaded. 我知道我可以在关联的测试中使用形式为fixture_objname.property的表达式访问灯具属性,因为YAML中指定的任何内容都会自动插入数据库并加载。 The problem with this is that I have to manually retype a bunch of property names for the object I just specified in the YAML, which seems silly. 问题在于,我必须为刚在YAML中指定的对象手动重新输入一堆属性名称,这似乎很愚蠢。

The documentation also says I can get the actual model instances by adding self.use_instantiated_fixtures = true to the test class. 该文档还说,我可以通过在测试类中添加self.use_instantiated_fixtures = true来获得实际的模型实例。 However, there don't seem to be any instance_methods that will dump out the fixture's model instance ( test_entry ) in a hash format to feed back into the .new method. 但是,似乎没有任何instance_methods会以散列格式转储夹具的模型实例( test_entry )以反馈给.new方法。

Is there an idiomatic way to get what I want, or a different, easier way? 有没有一种惯用的方式来获得我想要的东西,或者是一种更简单的方式?

I believe you're looking for something like: 我相信您正在寻找类似的东西:

entries(:test_entry).attributes
entries(:test_entry).attributes.class # => Hash

You can also remove properties if needed: 您还可以根据需要删除属性:

entries(:admin).attributes.except("id")

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM