【问题标题】:Checking whether the json response is right or not检查json响应是否正确
【发布时间】:2014-08-07 13:14:49
【问题描述】:

我从服务器收到 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

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

【问题讨论】:

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


    【解决方案1】:

    你应该解析JSON.parse(response.body),因为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
        }
    

    【讨论】:

    • 它仍然显示 (SyntaxError) "@type" : "test"
    • 我现在收到一个新错误... JSON::ParserError: A Json text must at least contains two octets!
    • 谢谢它的工作...如何在我的 Rails 控制台中打印 response.body 以检查...
    • 如果我对你有帮助,请点赞,read about hash rockets in ruby
    • 我不能投票,因为我需要它说的 15 票......以及如何在 Rails 控制台中打印 response.body。
    猜你喜欢
    • 2011-08-22
    • 2012-12-13
    • 2013-04-06
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    相关资源
    最近更新 更多