检查json响应是否正确

时间:2014-08-07 13:14:49

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

我从服务器获得了json响应。

{
    "@type": "res",
    "createdAt": "2014-07-24T15:26:49",
    "description": "test",
    "disabled": false
}

如何测试responseright还是wrong。以下是我的测试用例。

it "can find an account that this user belongs to" do 
    Account.find(id: @acc.id, authorization: @token);

    expect(response.status).to eq 200
    expect(response.body).to eq({
      "@type": "res",
      "createdAt": "2014-07-24T15:26:49",
      "description": "test",
      "disabled": false
    })
end

当我尝试执行测试时,它会引发很多语法错误。

1 个答案:

答案 0 :(得分:1)

你应该解析JSON.parse(response.body),因为正文为字符串:

it "can find an account that this user belongs to" do 
    Account.find(id: @acc.id, authorization: @token)
    valid_hash = {
      "@type" => "res",
      "createdAt" => "2014-07-24T15:26:49",
      "description" => "test",
      "disabled" => false
    }
    expect(response.status).to eq 200
    expect(JSON.parse(response.body)).to eq(valid_hash)
end

或者没有解析:

it "can find an account that this user belongs to" do 
    Account.find(id: @acc.id, authorization: @token)
    valid_hash = {
      "@type" => "res",
      "createdAt" => "2014-07-24T15:26:49",
      "description" => "test",
      "disabled" => false
    }
    expect(response.status).to eq 200
    expect(response.body).to eq(valid_hash.to_json)
end

更新,您hash语法无效:

 valid_hash = {
      "@type": "res",
      "createdAt": "2014-07-24T15:26:49",
      "description": "test",
      "disabled": false
    }

使用:

 valid_hash = {
      "@type" => "res",
      "createdAt" => "2014-07-24T15:26:49",
      "description" => "test",
      "disabled" => false
    }