ruby-on-rails - 如何使用 RSpec 检查 JSON 响应?

我的 Controller 中有以下代码:

format.json { render :json => { 
        :flashcard  => @flashcard,
        :lesson     => @lesson,
        :success    => true
} 

在我的 RSpec Controller 测试中,我想验证某个场景确实收到了成功的 json 响应,所以我有以下行:

controller.should_receive(:render).with(hash_including(:success => true))

虽然我在运行测试时收到以下错误:

Failure/Error: controller.should_receive(:render).with(hash_including(:success => false))
 (#<AnnoController:0x00000002de0560>).render(hash_including(:success=>false))
     expected: 1 time
     received: 0 times

我检查的响应有误吗?

最佳答案

您可以像这样解析响应正文:

parsed_body = JSON.parse(response.body)

然后,您可以针对已解析的内容做出断言。

parsed_body["foo"].should == "bar"

https://stackoverflow.com/questions/5159882/

相关文章:

json - 在 ASP.NET 中使用 WebAPI 或 MVC 返回 JSON

c# - 如何从 URL 获取 JSON 字符串?

android - 在 Android 中发送和解析 JSON 对象

json - 将 CSV/XLS 转换为 JSON?

json - 如何在 Github Wiki 中设置 JSON block 的样式?

javascript - JSON 劫持在现代浏览器中仍然是一个问题吗?

javascript - 将字符串转换为 JSON 对象

javascript - JSON.stringify 以 pretty-print 方式输出到 d

javascript - 序列化包含循环对象值的对象

javascript - 使用 JavaScript 遍历 JSON 对象树的所有节点