简体   繁体   English

如何在Rails yml固定装置中保持前导零?

[英]how to keep leading zeros in Rails yml fixtures?

I am trying to use the "food_descriptions" fixture in a "minitest" test in Rails 4 beta1: 我试图在Rails 4 beta1的“最小”测试中使用“ food_descriptions”固定装置:

butter:
 NDB_No:       "01001"
 FdGrp_Cd:     "0100"
 Long_Desc:    "Butter, salted"

The test I have is this: 我的测试是这样的:

it "must work" do
  food_descriptions(:butter).NDB_No.must_equal "01001"
end

However, when I run the test I get this error: Expected: "01001" Actual: 1001 I don't understand why that number is not recognized as a string. 但是,当我运行测试时,出现以下错误: 预期:“ 01001”实际:1001我不明白为什么该数字不能识别为字符串。 I've read that yml treats values that start with 0 as octal values, so adding the quotes should be enough to treat it as a string but is not working. 我读过yml将以0开头的值视为八进制值,因此添加引号应足以将其视为字符串,但不起作用。 I have also try the pipe "|" 我也尝试过管道“ |” sign but doesn't work either. 标志,但也不起作用。 Any idea why? 知道为什么吗?

Quick Answer (TL;DR) 快速解答(TL; DR)

  • YAML 1.2 leading zeros can be preserved by quoting a scalar value. 可以通过引用标量值来保留YAML 1.2前导零。

Context 上下文

  • YAML 1.2 YAML 1.2
  • Scalar value with leading zeros 带前导零的标量值

Problem 问题

  • Scenario: Developer wishes to specify a scalar value with leading zero in a YAML 1.2 file. 场景:开发人员希望在YAML 1.2文件中指定一个以零开头的标量值。
    • When parsed, the leading zero gets omitted or truncated 解析时,前导零会被忽略或截断

Solution

  • Quote a scalar value in YAML to have it parsed as a string. 在YAML中引用标量值以将其解析为字符串。
  • Leading zeros are preserved for non-numeric values. 非数字值保留前导零。

Pitfalls 陷阱

  • Data type casting for databases or programming language context may convert string scalar to numeric scalar value. 用于数据库或编程语言上下文的数据类型转换可能会将字符串标量转换为数字标量值。

It turns out the problem is not what I thought it was (yml). 原来问题不是我所想的(yml)。 The problem was that the fixtures were being pushed to the DB and the tests were actually retrieving the entry from the database (I thought the fixture were just in memory), and the database column type for that value was integer, not string, thus the leading zeros were being removed. 问题是这些夹具被推送到数据库,而测试实际上是从数据库中检索条目(我认为夹具只是在内存中),并且该值的数据库列类型是整数,而不是字符串,因此前导零被删除。 My real problem was that I wanted that column to be the primary key of the table of type string and I didn't realize that the migration I created didn't change the type of the column to string in the test database. 我的真正问题是,我希望该列成为字符串类型表的主键,并且我没有意识到我创建的迁移没有将测试数据库中列的类型更改为字符串。

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

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