简体   繁体   中英

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:

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. 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. I have also try the pipe "|" sign but doesn't work either. Any idea why?

Quick Answer (TL;DR)

  • YAML 1.2 leading zeros can be preserved by quoting a scalar value.

Context

  • 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.
    • When parsed, the leading zero gets omitted or truncated

Solution

  • Quote a scalar value in YAML to have it parsed as a string.
  • 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). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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