【问题标题】:Test datetime fields as a JSON string using rspec使用 rspec 将日期时间字段测试为 JSON 字符串
【发布时间】:2013-10-01 22:11:06
【问题描述】:

我正在尝试通过[the original object].to_json 和响应正文之间的相等性来测试带有 rspec(在 Rails 中)的 JSON 响应。问题是响应 JSON 字符串中的 updated_atcreated_at 字段与原始对象中的相同字段相差几毫秒,因此测试失败。

测试:

lesson = FactoryGirl.create(:lesson)
request.accept = "application/json"
get :show, {:id => lesson.to_param, :location_id => lesson.location_id}, valid_session
response.body.should eq lesson.to_json

结果:

expected: "{\"id\":1,\"location_id\":1,\"day_number\":5,\"time\":\"17:00\",\"min_age\":4,\"max_age\":10,\"created_at\":\"2013-10-02T00:51:53.870+03:00\",\"updated_at\":\"2013-10-02T00:51:53.870+03:00\"}"
        got: "{\"id\":1,\"location_id\":1,\"day_number\":5,\"time\":\"17:00\",\"min_age\":4,\"max_age\":10,\"created_at\":\"2013-10-02T00:51:53.000+03:00\",\"updated_at\":\"2013-10-02T00:51:53.000+03:00\"}"

请注意,这两个字符串是相等的,除了期望中的 870 毫秒(以及实际结果中的 000)。

我该如何测试?

【问题讨论】:

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


    【解决方案1】:

    通过比较来自 json 响应的日期时间与我的对象的 datetime_field.as_json,我以更好的方式完成了这一点:

    expect(json_body).to eq {
      order: {
        ordered_at: order.ordered_at.as_json 
    
        # ... other fields
      }
    }
    

    【讨论】:

      【解决方案2】:

      我会解析 JSON 响应 JSON.parse(response.body) 并验证:

      1) lesson.attributes.keys 包含与解析的 JSON 中完全相同的键;

      2) 检查除 created_atupdated_at 之外的每个值是否与解析后的 JSON 中的相应键值匹配。

      3) 如果您愿意,您也可以测试 created_atupdated_at 是否存在。

      【讨论】:

      • 对于这种特定情况,这绝对是合理的解决方法,但它不能解决匹配 created_atupdated_at 的问题
      【解决方案3】:

      我认为这种方式要好得多:

      JSON.parse(response.body).except('created_at', 'updated_at').should eq lesson.attributes.except('created_at', 'updated_at')
      

      【讨论】:

      • 我认为更好的选择是:expect(last_response.body).to eq course.attributes.to_json
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-04
      • 2016-06-13
      • 2021-04-29
      • 2022-08-18
      • 2016-07-19
      相关资源
      最近更新 更多