How to test JSON result from Ruby on Rails functional tests?

前端 未结 9 529
暗喜
暗喜 2021-01-29 23:35

How can I assert my Ajax request and test the JSON output from Ruby on Rails functional tests?

9条回答
  •  余生分开走
    2021-01-29 23:59

    In Rails >= 5

    Use ActionDispatch::TestResponse#parsed_body.

    Example:

    user = @response.parsed_body
    assert_equal "Mike", user['name']
    

    In Rails up to 4.x

    Use JSON.parse, which takes a string as input and returns a Ruby hash that the JSON represents.

    Example:

    user = JSON.parse(@response.body)
    assert_equal "Mike", user['name']
    

提交回复
热议问题