How to test JSON result from RoR functional tests

If your Rails controllers return JSON code, you have to call ActiveSupport::JSON.decode on the response body to get a hash to use in your functional tests.
First of all, add the code below on test/test_helper.rb file inside the ActionController::TestCase class:

# Added to support JSON test
def json
    ActiveSupport::JSON.decode @response.body

So, next step is make the JSON test. If you have an index method as below:

def index
    respond_to do |format|
        format.json { render json: }

The test below covers the HTML part:

test "should get index" do
    get :index
    assert_response :success
    assert_not_nil assigns(:user)

To cover also the JSON code, just add the following:

test "should get JSON index " do
    get :index , :format => :json
    assert_response :success
    assert_not_nil assigns(:user).to_json, @response.body

Check the doc to go in deep about encode e decode methods here,

Learn VIM


A great resources collection about VIM (expecially for Rails developer) by thoughtbot

“Unfortunately” some resources are not free, but it’s worth going to visit the website in any case.

Learn VIM