如何使用RSpec检查JSON响应?

发布于 2021-01-31 17:29:07

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

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

在我的RSpec控制器测试中,我想验证某个场景确实收到了成功的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

我是否检查响应不正确?

关注者
0
被浏览
71
1 个回答
  • 面试哥
    面试哥 2021-01-31
    为面试而生,有面试问题,就找面试哥。

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

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

    编辑

    将此更改为a post会比较麻烦。这是一种处理方法:

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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看