You can use the AssertJson gem for a nice DSL that allows you to check the keys and values ββthat should exist in your JSON response.
Add the gem to your Gemfile :
group :test do gem 'assert_json' end
This is a quick example of what your functional / controller test might look like (an example is an adaptation from 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 need to include the AssertJson module in your test and use the assert_json block, where you can check the response to existing and nonexistent keys and values. Hint: it is not immediately visible in README , but to check the value (for example, if your action just returns an array of strings), you can do
def test_my_action get :my_action, :format => 'json'
rkallensee Jan 14 '14 at 15:17 2014-01-14 15:17
source share