如何使用 RSpec 检查 JSON 响应? [英] How to check for a JSON response using RSpec?

查看:20
本文介绍了如何使用 RSpec 检查 JSON 响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器中有以下代码:

I have the following code in my controller:

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

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

In my RSpec controller test I want to verify that a certain scenario does receive a success json response so I had the following line:

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?

推荐答案

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

You can examine the response object and verify that it contains the expected value:

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

编辑

将其更改为 post 使其变得有点棘手.这是一种处理方法:

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 或真实的模型实例.

Note that mock_model will not respond to to_json, so either stub_model or a real model instance is needed.

这篇关于如何使用 RSpec 检查 JSON 响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆