我有一个端点,它响应从ActiveModelSerializer添加的对象的属性+属性。我想编写一个测试,检查响应是否有密钥。
让我们假设说对象(比如树)有这些键
expected_tree_attributes = [:height, :age, :color]
如何正确编写此测试?我能写一下:
subject { post :obtain_tree_info, { id: tree.id } }
response = JSON.parse(subject.body)
expected(response).to include(*expected_tree_attributes)
那是......可以接受吗?
答案 0 :(得分:0)
你可以这样做:
# api_matchers
response = JSON.parse(subject.body)
expect(response).to be_success
expect(response).to have_json_node(:height).with(tree.height)
expect(response).to have_json_node(:age).with(tree.age)
expect(response).to have_json_node(:color).with(tree.color)
# or
expect(response).to have_json_node(:age).with("123")
机载
describe 'sample spec' do
it 'should validate types' do
post '/api/v1/obtain_tree_info', {id: tree.id}
expect_json_types(height: :int, age: :int_or_null, color: :string)
end
end