How to check for a JSON response using RSpec?

后端 未结 14 1279
谎友^
谎友^ 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:53

    Another approach to test just for a JSON response (not that the content within contains an expected value), is to parse the response using ActiveSupport:

    ActiveSupport::JSON.decode(response.body).should_not be_nil
    

    If the response is not parsable JSON an exception will be thrown and the test will fail.

    0 讨论(0)
  • 2020-11-29 16:54

    You could parse the response body like this:

    parsed_body = JSON.parse(response.body)
    

    Then you can make your assertions against that parsed content.

    parsed_body["foo"].should == "bar"
    
    0 讨论(0)
提交回复
热议问题