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

时间:2014-08-09 12:49:45

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

我的模拟stub正确获得escaped,但API响应                                             一个人没有得到escaped

以下是我的Mock存根工厂。

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 Stub

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不同。

1 个答案:

答案 0 :(得分:2)

您要转换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\\\"}\""