如何测试Ruby on Rails功能测试中的JSON结果?
使用JSON gem的JSON.parse,它将一个字符串作为输入并返回一个JSON代表的Ruby散列。
下面是测试的基本要点是:
user = JSON.parse(@response.body)
assert_equal "Mike", user['name']
这里的创业板文档:http://json.rubyforge.org/。此外,你可以很容易地使用IRB中的JSON宝石。
对于简短的JSON响应,您可以简单地将JSON字符串与@ response.body进行匹配。这可以防止必须依靠另一个宝石。
assert_equal '{"total_votes":1}', @response.body
Rails已经JSON支持内置的:如果你正在使用的RSpec
assert_equal "Mike", json_response['name']
对于性能,你可能想要类似于: @json_response || = ActiveSupport :: JSON.decode @ response.body – 2011-03-05 01:36:12
Alex:不会缓存第一个响应测试并返回所有以下JSON测试? – iGEL 2011-03-25 20:51:44
:
def json_response
ActiveSupport::JSON.decode @response.body
end
无需插件
然后,你可以做这样的事情,json_spec值得一看
其实,你可以暗中使用JSON模块:
assert_equal assigns(:user).to_json, @response.body
可以使用AssertJson gem一个不错的DSL,它允许你检查应该在你的JSON存在键和值响应。
宝石添加到您的Gemfile
:
group :test do
gem 'assert_json'
end
这是一个简单的例子你的功能/控制器测试能看怎么样(的例子是从他们的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
您只需在测试中包含AssertJson
模块并使用assert_json
块,您可以在其中检查响应是否存在和不存在的键和值。提示:这是不是在README立即可见的,但检查的值(例如,如果你的行动只是返回一个字符串数组),你可以做
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
如前所述,使用JSON.parse测试JSON ,但是执行该断言的位置取决于您如何渲染JSON。
如果您在控制器中生成JSON,则可以在控制器功能测试中解析JSON(如显示其他答案)。如果您正在渲染JSON,使用Jbuilder,rabl或采用此方法的其他gem的视图,则parse the JSON in the view unit tests不是控制器功能测试。单元测试的执行速度通常更快并且易于编写 - 例如,您可以在内存中构建模型,而不是在数据库中创建模型。
没有一个答案提供了一个很好的可维护方法来验证JSON响应。我觉得这一个是最好的:
https://github.com/ruby-json-schema/json-schema
它提供了一个很好的实现了标准json schema
你可以写这样一个模式:
schema = {
"type"=>"object",
"required" => ["a"],
"properties" => {
"a" => {
"type" => "integer",
"default" => 42
},
"b" => {
"type" => "object",
"properties" => {
"x" => {
"type" => "integer"
}
}
}
}
}
,并用它喜欢: JSON::Validator.validate(schema, { "a" => 5 })
对我的Android客户端实现进行验证的最佳方法。
不错,很容易 - 谢谢你:) – 2016-02-12 18:30:30