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
end

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

def index
    respond_to do |format|
        format.html
        format.json { render json: UserDatatable.new(view_context) }
    end
end

The test below covers the HTML part:

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

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
end

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

Leave a Reply

Your email address will not be published. Required fields are marked *