【问题标题】:Why is my JSON created via the `Factory` different from the one i am getting from `API`.为什么我通过“Factory”创建的 JSON 与从“API”获得的 JSON 不同。
【发布时间】:2014-08-09 12:49:45
【问题描述】:

我的模拟 stub 正确地得到了 escaped,但是 API 响应 一个没有得到escaped

下面是我的模拟存根工厂。

require 'faker'

FactoryGirl.define do 
    factory :account do |f|
        f.name {Faker::Name.name}
        f.description {Faker::Name.description}     
    end

    factory :account_json, class: OpenStruct do
    send :'@type' , "accountResource"
        createdAt "2014-08-07T14:31:58"
        createdBy "2"
        updatedAt "2014-08-07T14:31:58"
        updatedBy "2"
        accountid "2055"
        name "Test"
        description "Something about Test"
        disabled "false"
    end

end

以下是我正在构建工厂存根并尝试将其与 API 响应进行比较的规范。

it "can find an account that this user belongs to" do 
    account = Account.find( id: 2055, authorization: @auth )        
    hashed_response = FactoryGirl.build(:account_json).marshal_dump.to_json
    expect(account.to_json).to eq(hashed_response.to_json);
end

API 响应和存根

FactoryGirl 存根

expected: "\"{\\\"@type\\\":\\\"accountResource\\\",\\\"createdAt\\\":\\\"2014-08-07T14:31:58\\\",\\\"createdBy\\\":\\\"2\\\",\\\"updatedAt\\\":\\\"2014-08-07T14:31:58\\\",\\\"updatedBy\\\":\\\"2\\\",\\\"accountid\\\":\\\"2055\\\",\\\"name\\\":\\\"Test\\\",\\\"description\\\":\\\"Something about Test\\\",\\\"disabled\\\":\\\"false\\\"}\"

API 响应

got: "{\"@type\":\"accountResource\",\"createdAt\":\"2014-08-07T14:31:58\",\"createdBy\":2,\"updatedAt\":\"2014-08-07T14:31:58\",\"updatedBy\":2,\"accountid\":2055,\"name\":\"Test\",\"description\":\"Something about Test\",\"disabled\":false}"

为什么我通过 Factory 创建的 JSON 与我从 API 获得的 JSON 不同。

【问题讨论】:

    标签: ruby-on-rails ruby json ruby-on-rails-4 rspec


    【解决方案1】:

    您正在转换 hashed_response to_json 两次 - 一次在规范的第二行,一次在第三行。删除to_json 方法调用之一。

    例如:

    2.0.0-p247 :005 > {"@type" => "accountResource"}.to_json
     => "{\"@type\":\"accountResource\"}" 
    2.0.0-p247 :006 > {"@type" => "accountResource"}.to_json.to_json
     => "\"{\\\"@type\\\":\\\"accountResource\\\"}\"" 
    

    【讨论】:

    • 这有效,但仍然失败......最后一个键和值似乎很奇怪...... paste.org/9457936
    • 禁用属性的值 false 有反斜杠
    • 那是因为你告诉你的规范期待字符串 "false" 而你得到的是 FalseClass false
    • 我如何单独与属性进行比较...现在它检查键和值...我如何检查它是否仅具有属性。
    • @UnderTaker 在将 json 解析为 ruby​​ 哈希后,您可以调用 #keys 来获取键列表...这是您想要的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    • 2020-05-27
    • 2019-07-29
    • 1970-01-01
    • 2018-08-20
    • 1970-01-01
    相关资源
    最近更新 更多