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

前端 未结 9 513
暗喜
暗喜 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-30 00:03

    In newer versions of rails, you can leverage parsed_body to get access to this in your tests without any work.

    Calling parsed_body on the response parses the response body based on the last response MIME type.

    Out of the box, only :json is supported. But for any custom MIME types you've registered, you can add your own encoders...

    https://api.rubyonrails.org/v5.2.1/classes/ActionDispatch/IntegrationTest.html

    0 讨论(0)
  • 2021-01-30 00:10

    None of the answers provides a nice maintainable way to verify a JSON response. I find this one to be the best:

    https://github.com/ruby-json-schema/json-schema

    It provides a nice implementation for the standard json schema

    You can write a schema like:

    schema = {
        "type"=>"object",
        "required" => ["a"],
        "properties" => {
            "a" => {
                "type" => "integer",
                "default" => 42
            },
            "b" => {
                "type" => "object",
                "properties" => {
                    "x" => {
                        "type" => "integer"
                    }
                }
            }
        }
    }
    

    and use it like: JSON::Validator.validate(schema, { "a" => 5 })

    Best way to verify it against my android client implementation.

    0 讨论(0)
  • 2021-01-30 00:14

    Rails has JSON support built in:

    def json_response
        ActiveSupport::JSON.decode @response.body
    end
    

    No need for a plugin

    Then you can do something like this:

    assert_equal "Mike", json_response['name']
    
    0 讨论(0)
提交回复
热议问题