I have the following code in my controller:

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

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

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

Although when I run my tests I get the following error:

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

Am I checking the response incorrectly?

推荐答案

您可以判断响应对象并验证它是否包含预期值:

@expected = { 
        :flashcard  => @flashcard,
        :lesson     => @lesson,
        :success    => true
}.to_json
get :action # replace with action name / params as necessary
response.body.should == @expected

EDIT

Changing this to a post makes it a bit trickier. Here's a way to handle it:

 it "responds with JSON" do
    my_model = stub_model(MyModel,:save=>true)
    MyModel.stub(:new).with({'these' => 'params'}) { my_model }
    post :create, :my_model => {'these' => 'params'}, :format => :json
    response.body.should == my_model.to_json
  end

请注意,mock_model不会响应to_json,因此需要stub_model或真实的模型实例.

Json相关问答推荐

如何在PowerShell中扩展JSON中的嵌套数组

无法从JSON解析ZonedDateTime,但可以使用格式化程序很好地解析

Vega-Lite(Deneb):难以将最小和最大值应用于折线图和文本标签以及线条末尾的点

在Reaction中从JSON文件中筛选数组

在Jolt中将具有嵌套元素的对象数组转换为单独的对象列表

重构JOLT代码以获得预期输出

在 NX 工作区中跨多个应用共享 ngx-translate 翻译文件

从 Inno Setup 中的 JSON 文件的每个对象中读取特定字符串

jq - 将父键值提取为子元素旁边的逗号分隔值

如何在不使用 Newtonsoft.JSON 的情况下序列化/反序列化

如何在 Postman 中匹配 json 响应中的内容?并可视化

如何为包含一些固定值并可能具有其他附加值的数组字符串创建数组 json 架构

Play Framework:如何序列化/反序列化与 JSON 的枚举

JSON Schema 与 XML Schema 的比较及其future

使用非美国日期格式时,JsonConvert.DeserializeObject 无法将字符串转换为 DateTime

Newtonsoft Json 将值 {null} 转换为类型System.Int32时出错

JSON.NET JsonConvert 与 .NET JavaScriptSerializer

ASP.NET MVC 读取原始 JSON 发布数据

Sequelize - 如何仅返回数据库结果的 JSON 对象?

Java HashMap 与 JSONObject