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

前端 未结 9 532
暗喜
暗喜 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:56

    You can use the AssertJson gem for a nice DSL which allows you to check for keys and values which should exist in your JSON response.

    Add the gem to your Gemfile:

    group :test do
      gem 'assert_json'
    end
    

    This is a quick example how your functional/controller test could look like (the example is an adaption from their README):

    class ExampleControllerTest < ActionController::TestCase
      include AssertJson
    
      def test_my_action
        get :my_action, :format => 'json'
        # => @response.body= '{"key":[{"inner_key":"value1"}]}'
    
        assert_json(@response.body) do
          has 'key' do
            has 'inner_key', 'value1'
          end
          has_not 'key_not_included'
        end
      end
    
    end
    

    You just have to include the AssertJson module in your test and use the assert_json block where you can check the response for existent and non-existant keys and values. Hint: it's not immediately visible in the README, but to check for a value (e.g. if your action just returns an array of strings) you can do

      def test_my_action
        get :my_action, :format => 'json'
        # => @response.body= '["value1", "value2"]'
    
        assert_json(@response.body) do
          has 'value1'
          has 'value2'
          has_not 'value3'
        end
      end
    

提交回复
热议问题