【问题标题】:how to check/test specific field in json using rspec如何使用 rspec 检查/测试 json 中的特定字段
【发布时间】:2013-04-01 06:53:01
【问题描述】:

这是我的 rspec 代码:-

  it "which has max value" do
    get :index, Devise.token_authentication_key => @user.authentication_token, business_id: @business.id, max: '1'
    expect(request.flash[:alert]).to eq(nil)
    expect(response.body).to eq([@location].to_json(LocationFinder::API_PARAMS.merge(:root => false)))
  end

测试结果是-

预期:“[{\"address\":\"1120 Milky Way\",\"business_id\":1,\"city\":\"Cupertino]"

  got: "[{\"address\":\"1120 Milky Way\",\"business_id\":1,\"city\":\"Cupertino,\"distance\":260.33452958767384,]"

这里的距离是一个额外的字段,我如何检查特定字段,或者如果不可能,如何消除 rspec 未检查的“距离”字段。

【问题讨论】:

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


    【解决方案1】:

    您可以使用以下方式检查各个字段:

    # get the first entry in the JSON array
    json_response = JSON.parse(response.body).first
    
    # compare each field
    expect(json_response['address']).to eq(@location.address)
    expect(json_response['business_id']).to eq(@location.business_id)
    expect(json_response['city']).to eq(@location.city)
    

    当然,您可能需要根据您的实施调整在 @location 上调用的确切方法,但这就是要点。

    【讨论】:

      猜你喜欢
      • 2015-11-15
      • 2012-03-07
      • 1970-01-01
      • 1970-01-01
      • 2020-06-19
      • 2011-07-06
      • 2020-01-17
      • 1970-01-01
      • 2020-05-09
      相关资源
      最近更新 更多