How to check for a JSON response using RSpec?

后端 未结 14 1281
谎友^
谎友^ 2020-11-29 16:03

I have the following code in my controller:

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


        
14条回答
  •  情深已故
    2020-11-29 16:29

    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
    

    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
    

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

提交回复
热议问题